By-catch exception: when not to catch them?

I wrote a small number of small libraries (a bunch of classes) for my application inside the PHP Zend Framework. I also took advantage of these exceptions inside the library methods themselves and wrote them to a file.

Then, suddenly, I came across a problem that the main application using these libraries will not exit due to errors even in situations that I expected them to stop working due to a fatal error. The problem with this was that the code below was executed to the end, which he shouldn't have.

It seemed that it was nice to catch and possibly record most (except in special cases) of errors within the library classes. They should always throw a mistake, as is? Will this be the correct assumption?

I would appreciate it if anyone could answer for this for me.

+4
source share
3 answers

The general philosophy of exceptions in any language is that they report exceptional circumstances. You must use them accordingly.

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

If you can't think of anything better than aborting and propagating the error, then there is no point in catching the exception. On the other hand, if there are some mistakes that you can reasonably react with, catch them and collapse something else.

A typical example is the processing of a large number of files. If there is an error in the parsing logic, you cannot do anything, even if many parsing of functions can occur during parsing. However, in the main loop, you can try analyze each file, and if there is an exception, you will catch it, skip the file and move on to the next.

If you are writing a library function, you may need one last try block surrounding your entire function; which is somewhat up to you. Just clearly document what exceptions the user should expect from your library.

+6
source

Capturing and handling all exceptions is a good idea. If you don’t know for sure that the exception is safe to ignore (for example, one thrown by your own code), display the error page. Don't just re-drop it because there is nothing worse than presenting a blank page or the default error page of a web server β€” or even a PHP error message β€” to the user.

+4
source

It depends on whether the website 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 expect an error that can cause a fatal problem, then catch and process it.

0
source

All Articles