Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should be the best Exception Handling Strategy

I am working on application where user invokes a method from UI , on this I am calling a method from business class which calls another methods

UI--> Method1 -->Method2 --> Method3

I want to display the error message to user if any exception occurs in any of the method.

Shall I go with throwing the exception directly to the caller method and at the UI layer I will catch exception and display the message.

Apart from Throwing exceptions and catching it at caller is there any better way to handle it?

I do not want to use the C++ convention where integer is returned as the result.

like image 653
Ram Avatar asked Jul 07 '10 10:07

Ram


2 Answers

If you can't recover from the exception in the method where the exception happens, don't try to catch it (unless you want to log it, in which case throw it again after logging). Then catch at the UI-level.

Trying to catch exceptions at every level just adds bloat to your code.

like image 110
Dr Herbie Avatar answered Nov 15 '22 13:11

Dr Herbie


When you design a multi-tier application, you should keep in mind that those tiers can be distributed, maybe hosted within different services on different machines, thus making it necessary to throw exceptions through remote boundaries which is not a very preferable way to do. In such a case, catching them and just bubbling some sort of error message or code is a better way in my opinion. Additionally you should allways trace the exception when you catch it. Its always good to know whats going on in your application.

like image 40
oldbread Avatar answered Nov 15 '22 13:11

oldbread