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.
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.
Catching and handling all exceptions is a good idea. If you don't know for sure the exception is safe to ignore (e.g. one thrown by your own code), display an error page. Do not simply re-throw it since there's nothing worse than presenting a blank page or the default error page of the webserver - or even a PHP error message - to the user.
It depends if the web site is in production or is a released product. The last thing you want to do is show the user a stack trace for example. If you're expecting an error which could cause a fatal problem, then catch and handle it.
精彩评论