An exception is unexpected program result that can be handled by the program itself. Exception Handling in PHP is almost similar to exception handling in all programming languages.
PHP provides following specialized keywords for this purpose.
- try: It represent block of code in which exception can arise.
- catch: It represent block of code that will be executed when a particular exception has been thrown.
- 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.
Why Exception Handling in PHP ?
Following are the main advantages of exception handling over error handling
- Separation of error handling code from normal code: In traditional error handling code there is always if else block to handle errors. These conditions and code to handle errors got mixed so that becomes unreadable. With try Catch block code becomes readable.
- Grouping of error types: In PHP both basic types and objects can be thrown as exception. It can create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types.
Exception handling in PHP:
- Following code explains the flow of normal try catch block in PHP:
<?php// PHP Program to illustrate normal// try catch block codefunctiondemo($var) {echo" Before try block";try{echo"\n Inside try block";// If var is zero then only if will be executedif($var== 0){// If var is zero then only exception is thrownthrownewException('Number is zero.');// This line will never be executedecho"\n After throw (It will never be executed)";}}// Catch block will be executed only// When Exception has been thrown by try blockcatch(Exception$e) {echo"\n Exception Caught",$e->getMessage();}// This line will be executed whether// Exception has been thrown or notecho"\n After catch (will be always executed)";}// Exception will not be riseddemo(5);// Exception will be rised heredemo(0);?>chevron_rightfilter_noneOutput:Before try block Inside try block After catch (will be always executed) Before try block Inside try block Exception CaughtNumber is zero. After catch (will be always executed)
- Following code explains the flow of normal try catch and finally block in PHP
<?php// PHP Program to illustrate normal// try catch block codefunctiondemo($var) {echo" Before try block";try{echo"\n Inside try block";// If var is zerothen only if will be executedif($var== 0) {// If var is zero then only exception is thrownthrownewException('Number is zero.');// This line will never be executedecho"\n After throw it will never be executed";}}// Catch block will be executed only// When Exception has been thrown by try blockcatch(Exception$e) {echo"\n Exception Caught".$e->getMessage();}finally {echo"\n Here cleanup activity will be done";}// This line will be executed whether// Exception has been thrown or notecho"\n After catch it will be always executed";}// Exception will not be riseddemo(5);// Exception will be rised heredemo(0);?>chevron_rightfilter_noneOutput:Before try block Inside try block Here cleanup activity will be done After catch (will be always executed) Before try block Inside try block Exception CaughtNumber is zero. Here cleanup activity will be done After catch (will be always executed)
- Using Custom Exception Class
<?phpclassmyExceptionextendsException {functionget_Message() {// Error message$errorMsg='Error on line '.$this->getLine().' in '.$this->getFile().$this->getMessage().' is number zero';return$errorMsg;}}functiondemo($a) {try{// Check ifif($a== 0) {thrownewmyException($a);}}catch(myException$e) {// Display custom messageecho$e->get_Message();}}// This will not generate any exceptiondemo(5);// It will cause an exceptiondemo(0);?>chevron_rightfilter_noneOutput:Error on line 20 in /home/45ae8dc582d50df2790517e912980806.php0 is number zero
- Set a Top Level Exception Handler: The set_exception_handler() function set all user defined function to all uncaught exception.
<?php// PHP Program to illustrate normal// try catch block code// Function for Uncaught ExceptionfunctionmyException($exception) {// Details of Uncaught Exceptionecho"\nException: ".$exception->getMessage();}// Set Uncaught Exception handlerset_exception_handler('myException');functiondemo($var) {echo" Before try block";try{echo"\n Inside try block";// If var is zero then only if will be executedif($var== 0){// If var is zero then only exception is thrownthrownewException('Number is zero.');// This line will never be executedecho"\n After throw (it will never be executed)";}}// Catch block will be executed only// When Exception has been thrown by try blockcatch(Exception$e) {echo"\n Exception Caught",$e->getMessage();}// This line will be executed whether// Exception has been thrown or notecho"\n After catch (will be always executed)";if($var< 0) {// Uncaught ExceptionthrownewException('Uncaught Exception occurred');}}// Exception will not be riseddemo(5);// Exception will be rised heredemo(0);// Uncaught Exceptiondemo (-3);?>chevron_rightfilter_noneOutput:Before try block Inside try block After catch (will be always executed) Before try block Inside try block Exception CaughtNumber is zero. After catch (will be always executed) Before try block Inside try block After catch (will be always executed) Exception: Uncaught Exception occurred
Recommended Posts:
- Exception handling in JSP
- Exception Handling in Node
- PHP | Basics of File Handling
- Error handling in PHP
- How to rethrow an exception in JavaScript, but preserve the stack?
- How to get JavaScript stack trace when throw an exception ?
- Why does canvas.toDataURL() throws a security exception?
- Javascript | Error and Exceptional Handling With Examples
- File handling in Node.js
- JavaScript Error Handling: Unexpected Token
- Handling User-Agents in Node.js
- Error Handling in Express
- Error Handling in ElectronJS
- Handling 404 Error in Flask
- Form Handling using EasyUI Framework
- PHP 5 vs PHP 7
- PHP | Get PHP configuration information using phpinfo()
- PHP | php.ini File Configuration
- How to import config.php file in a PHP script ?
- LAMP installation and important PHP configurations on Ubuntu
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

