Change language

PHP Exception Handling

An exception is an unexpected program result that can be handled by the program itself. The exception handling in PHP is almost the same as the exception handling in all programming languages.
PHP provides the following specialized keywords for this purpose.
  • try:it represents a block of code in which an exception may be thrown.
  • catch:represents a block of code that will be executed when a specific exception is thrown.
  • throw:is used to throw an exception. It is also used to list exceptions that a function throws but does not handle itself.
  • last:it is used instead of a catch block or after a catch block, it is mainly used for cleanup in code PHP.
Why PHP does exception handling?
The following are the main advantages of exception handling over error handling.
  • Separating error handling code from normal code:Traditional error handling code always has an if else block to handle errors. These conditions and the error handling code were messed up, making it unreadable. When you try to Catch, the code block becomes readable.
  • Grouping error types:In PHP, both base types and objects can be thrown as an exception. It can create a hierarchy of exception objects, group exceptions in namespaces or classes, and classify them by type.
Exception handling in PHP:
  • The following code explains the flow of a normal try catch block in PHP:  
    // PHP program to illustrate normal
    // try to catch the block code function demo ( $var ) { echo "Before try block" ; try { echo "Inside try block" ; // If var is zero, then only if executed if ( $var == 0) {   // If var is zero, only an exception is thrown throw new Exception ( ’Number is zero.’ ); // This line will never be executed echo "After throw (It will never be executed)" ; } } // Capture block will only be executed // When an exception was thrown by a try block catch (Exception $e ) { echo "Exception Caught" , $e -> getMessage(); } // This line will be executed // Exception was thrown or not echo "After catch (will be always executed)" ; }  
    // The exception will not be raised
    demo (5);  
    // Exception will be promoted here
    demo (0);
    ?>
    Exit:
    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) 
  • The following code explains the flow of regular try catch and finally commands in PHP  
    // PHP program to illustrate normal // try to catch the block code function demo ( $var ) { echo "Before try block" ; try { echo "Inside try block" ; // If var is zero, only if executed if ( $var == 0) { // If var is zero, exception only throw new Exception ( ’Number is zero.’ ); // This line will never be executed echo "After throw it will never be executed" ; } } // Capture block will only be executed // When an exception was thrown by a try block catch (Exception $e ) { echo "Exception Caught" . $e -> getMessage(); } finally { echo "Here cleanup activity will be done" ; } // This line will be executed // Exception was thrown or not echo "After catch it will be always executed" ; }  
    // The exception will not be raised
    demo (5);  
    // Exception will be promoted here
    demo (0);
    ?>
    Exit:
    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 class myException extends Exception { function get_Message() { // Error message $errorMsg = ’Error on line’ . $this -> getLine(). ’in’ . $this -> getFile() . $this -> getMessage(). ’is number zero’ ; return $errorMsg ; } } function demo ( $a ) { try { // Check if if ( $a == 0) { throw new myException ( $a ); } } catch (myException $e ) { // Show custom message echo $e -> get_Message(); } }  
    // This will not throw any exceptions
    demo (5);  
    // This will throw an exception
    demo (0);
    ?>
    Exit:
    Error on line 20 in /home/45ae8dc582d50df2790517e912980806.php0 is number zero 
  • Setting a top-level exception handler:The set_exception_handler() function sets all custom functions on all unhandled exceptions.  
    // PHP program to illustrate normal
    // try to catch the block code 
    // Function for unhandled exception function myException ( $exception ) {   // Uncaught Exception Details echo "Exception:" . $exception -> getMessage(); }  
    // Set the Uncaught Exception handler set_exception_handler ( ’myException’ ); function demo ( $var ) { echo " Before try block " ; try { echo "Inside try block" ; // If var is zero, then only if executed if ( $var == 0) {   // If var is zero, only an exception is thrown throw new Exception ( ’Number is zero.’ ); // This line will never be executed echo "After throw (it will never be executed)" ; } } // Capture block will only be executed // When an exception was thrown by a try block catch (Exception $e ) { echo "Exception Caught" , $e -> getMessage(); } // This line will be executed // An exception was thrown or not echo " After catch (will be always executed) " ; if ( $var < 0) { / / Uncaught Exception throw new Exception ( ’Uncaught Exception occurred’ ); } }  
    // The exception will not be promoted
    demo (5);  
    // Exception will be promoted here
    demo (0);  
    // Uncaught Exception
    demo (-3);
    ?>
    Exit:
    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 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically