Okay, its a very lame question for many but I hope I will have overwhelming response :)
When I throw an Exception in PHP I can add a code to the message.
I catch an exception and handle it according to its type (Like InvalidArgumentException
or OutOfBoundException
). I log the message or display it or do whatever is suitable.
I can add also append a previous exception to trace a path to the origin of the error.
BUT one thing I have never used or never thought of: how useful is code?
For example:
throw new Exception("db Error", $code, $previousException);
What do I do with $code
?
With PHP 5 came a new object oriented way of dealing with errors. Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.
Throwing a generic exception is almost as simple as it sounds. All it takes is to instantiate an exception object—with the first parameter of the Exception constructor being the error message—and then, "throw" it. The most important thing to take note of is the message.
throw: It is used to throw an exception. It is also used to list the exceptions that a function throws, but doesn't handle itself. finally: It is used in place of catch block or after catch block basically it is put for cleanup activity in PHP code.
The default error handling in PHP is very simple. An error message with filename, line number and a message describing the error is sent to the browser. Exceptions are used to change the normal flow of a script if a specified error occurs. This can be done using PHP die() Function.
The message is for display to the user, while the code is for use by your program. So for example, in your "database error" example, you might make up a set of codes like
and then use the appropriate code. Then when other parts of your code saw they exception, they would know what happened and could possibly deal with it intelligently.
How $code
is interpreted is dependent on the exception type. For example, if you have an Exception
subclass that represents a MySQL database error, then the $code
could be the native MySQL error code. In the case of a low-level IO error, this could be a value from <errno.h>
.
Basically, $code
should contain whatever you need to programmatically handle an exception. Most exceptions are meant to be handled somewhere. If all of your exceptions are simply displayed as errors, then $code
is only useful if you need to include an error code from a library like the MySQL client library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With