Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception catching: when not to catch them?

I had been writing number of small libraries (bunch of classes) for my application inside PHP's Zend Framework. I had also been catching these exceptions inside the library's methods itself and logging them to a file.

Then suddenly I ran to an issue that my main application that was using these libraries would not quit due to errors even in situations I expected them to quit due to a fatal error. The problem with this was the code below kept executing till the end - which it should not have.

It seems like its not a good practice to catch and perhaps log majority (except in special cases) of the errors inside the library classes. They should always throw the error as it is? Would that be a correct assumption?

I'd appreciate if anyone could answer this for me.

like image 307
Subrat Basnet Avatar asked Dec 28 '22 14:12

Subrat Basnet


1 Answers

The general philosophy of exceptions, in any language, is that they communicate exceptional circumstances. You should use them accordingly.

If you end up surrounding every function call with a try block, something is wrong. Exceptions are precisely designed to make error handling logical and not require the programmer to track all possible error paths. Therefore, you should catch exceptions precisely at those points where you can respond meaningfully to them.

If you cannot think of anything better to do than to abort and propagate the error, then there's no point catching an exception. On the other hand, if there are some errors to which you can react sensibly, catch those, and rethrow anything else.

A typical example is if you're processing lots of files. If there's an error anywhere inside the parsing logic, there's nothing you can do, even though parsing may go down many function calls. However, at the main loop you can try parsing each file, and if there's an exception, you catch that, skip the file and continue with the next one.

If you're writing a library function, you might want to have one final try block surrounding your entire function; that's somewhat up to you, though. Just document cleanly which exceptions the user has to expect from your library.

like image 113
Kerrek SB Avatar answered Dec 30 '22 11:12

Kerrek SB