Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store PHP Exceptions in array

I am really not sure if this is the right way to go, since exceptions is really a fresh subject to me. Is it possible to catch multiple exceptions (let the execution of the script continue) and then store the exceptions in a array to be able to return all exceptions caused?

By that said, it would be awesome to be able to use exceptions to more than just showing an error that kills the application (script)

Thanks!

like image 755
Industrial Avatar asked Nov 29 '22 18:11

Industrial


1 Answers

At first, exception handling is not as trivial as it looks like, so you should invest a little time in this. :-)

You should look at exceptions explicit as an error you can't handle in the current code/function. If you can solve the problem, there is no need to throw and handle an exception.
Don't use it as mechanism to handle expected behavior.

Sure it is possible to catch multiple exceptions, continue the code execution and store them in an array, but it doesn't make sense. You through an exception in your code if you really encounter an error you cannot deal with in your current code (for example suddenly closed sockets, etc.). The rule then is:
Only catch an exception if you can do something useful with it or throw another exception

For tracking errors in your application you should use other techniques than storing them in an array and retrieving them later. Use Logging (there are excellent frameworks for example Log4PHP) to document minor application errors and warnings.

By that said, it would be awesome to be able to use exceptions to more than just showing an error that kills the application (script)

An exception should kill the application only in the case there is nothing you can do about it. Also in most cases it is a good idea to catch all exceptions on the highest level in your script, log the error with a stack trace and present the user a nice error message instead of just "kill" everything. :-)

For just some syntax examples see W3Schools PHP Exception Handling. A larger article about this topic is posted on Devshed.

like image 143
echox Avatar answered Dec 02 '22 10:12

echox