Today I come with the new article which is about the OOPs concept in PHP. I am sure all developers have faced errors at the time of code execution(sometimes) because of malicious data and even perfectly good code may produce runtime errors so PHP has an option to deal with errors which are known as Exception.
Read about: Type Hinting in PHP5
Here is the topic about Exception in PHP which I am going to explain in this article:
1. What is Exception?
2. Main usage of Exception
3. Exception Handlers
4. Default Exception Handler function
5. Advantage and Disadvantage of the Exception
6. Extending the Exception Class
7. Example of the Extending Exception
What is Exception?
The exception is designed to handle situations when errors appear in the program. The exception is useful when runtime abnormal conditions arise in a program.Exceptions are introduced in PHP5.
Basic Syntax :
1 2 3 4 | (exception $e). e is an object of class. |
Here is a simple example that shows an Exception being thrown and caught:
1 2 3 4 5 6 7 8 9 | try { throw new Exception; //unreached code } catch (Exception $e) { //Exception caught } |
Main Usage of Exception
Exceptions are an extremely powerful way to report run time error and robust error-handling method in PHP.You can use exception handling any kind of Possibilities and trigger an Exception
PHP have some exception handlers that display the exception. If you don’t use exception handler on your program and if any error occurs, it will stop your program execution but if you used an exception handler, program will continue to run with exception and it is known as exception handling.
Three Exception Handlers are used by exceptions::
Exception Handlers:
Predefined keywords for Exception in PHP are
1) Try-catch
3) Throw
4) Try-Finally
Let’s start with try-catch block for handling exception
1) Try-Catch:
Try is a block of code which caught an error and catch accept the exception thrown by try block and also handle the exception.
Here, If your code throws an error which is written in a Try block so execution of code is halted and it jump ahead to the catch block. Catch catches an Exception. The catch is normally used to perform the action that might be necessary from the error occurred.
Also Read: Static Keyword in PHP
NOTE: try statement without catch or finally is Invalid.
SYNTAX:
1 2 3 4 5 6 7 8 9 10 | try { // Normal execution code lines } catch() { // Exception handling code lines } |
NOTE: You can’t use try on single statement. It must be surrounded by { } parenthesis.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | Class CustomException { function Runnable() { try { $db = mysql_select_db(); $result = mysql_query('SELECT id from table where_condition'); $row = mysql_fetch_row($result); } catch (Exception $e) { var_dump($e->getMessage()); } } } $obj = new CustomException(); $obj->Runnable(); |
Like above you can see, the exception will be a trigger for an invalid query syntax in the code.you can enclose the entire code with a try/catch block and handle an error if one occurs.
You can use multiple catch blocks if you want to handle different errors differently, but you cannot use multiple try blocks, only one try block is allowed.
Here is the SYNTAX of multiple catch blocks: The syntax of try with multi-catch is as follows:
1 2 3 4 5 6 7 8 9 | try { // Normal execution code lines } catch (SomeException e) { // Exception handling code lines } catch (SomeOtherException e) { // Exception handling code lines } |
Here, When an exception is occurred the first catch() is called and if the result is true, the catch block is entered and the exception message display and If the result is false, the next catch statement is checked.
2) Throw
Throw is a new exception used to generate an exception manually in an own code.After detect an error using the throw statement, you can easily return to the exact point in the code which is responsible to handle execution of the program and continue to code execution because throw executes until it detects an appropriate try/catch block.
The catch block catches the exception and if any new exception occurs and catch block fails to handle that exception uncaught error occur. So using throw, You can do this by throwing an exception to catch block.
The throw statement
1 2 3 | throw <Throwableobject>; |
SYNTAX:
1 2 3 4 5 6 7 8 9 10 11 | try { $name = $_GET['name']; if(!$name) { throw new Exception(); } } catch (Exception $e) { } |
To throw an object which does not inherit from class Exception will result in a final runtime error.
NOTE : throw can only throw an object. You can’t throw strings or integers.
3) Try – Finally
Finally is also code block which will be executed if an exception occurs or not. This is a code block which gives assurance to be executed at least once when your program execute if the program has an any error or not.
SYNTAX:
1 2 3 4 5 6 7 8 9 10 | try { // Normal execution code lines } finally { // Exception handling code lines } |
All of the above methods are valid. You can use any of method. It’s just a matter of taste and style.
If the exception is not caught anywhere of any of above method PHP have another option to achieve exception is exception-handling function set_exception_handler():
Default Exception Handler function:
An interesting feature in PHP is that PHP has an ability to install a default exception handler that will be called if an exception reaches the top scope and still has not been caught. Default Exception Handler is totally different from a try-catch block. it is a single function that will handle any uncaught exception.
The default exception handler is very useful when you want to prevent a user from being returned an error of an uncaught exception.
You can define a function to set a default exception handler with a single parameter:
1 2 3 | function default_exception_handler($exception) {} |
You can use above function into set_exception_handler:
1 2 3 | $handler = set_exception_handler('default_exception_handler'); |
set_exception_handler is replaced built-in behavior of exception when an uncaught exception occurs to the page.This handler has the ability to handle certain error conditions differently.
And to restore the previously defined exception handler following function is used:
1 2 3 | restore_exception_handler(); |
Default Exception Handler gives the flexibility to handle an error instead of wrapping every statement into an individual try block.
Advantages and Disadvantages:
Advantages:
1. You don’t have to place if() statements in every place where an exception might occur.
2. Exceptions are greatly increased the reliability of your code if properly used.
Disadvantages:
1. PHP does not support the use of throws() methods like Java and other languages.
2. Unlike other languages, native PHP errors are displayed to the client-side are not mapped to exceptions yet
Extending the Exception Class
PHP has a built-in Exception class which is specifically designed for exceptions. In a simple manner, Exceptions are just objects that you can “throw” to PHP. PHP allows to define own classes that inherit from the inbuilt Exception class.
Example of Extending the Exception Class
The following code snippet shows how to extend the built-in exception class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class CustomException extends Exception { public $err; function __construct($err) { // Normal execution code lines $this->err = $err; } } try { } catch (CustomException $e) { print "Caught an CustomException with err $obj->err"; } catch (Exception $e) { print "Caught unrecognised exception"; } |
The exception is a huge topic and here it just outlined so you can start using them immediately.I hope above explanation, You will understand the concept and put it to good use in your code. If you have any query, please share in the comment section. 🙂