Exception handling in php

Different error handling methods

Exception handling in php

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. PHP has an exception model similar to that of other programming languages. We will show different error handling methods:

  • Basic use of Exceptions
  • Creating a custom exception handler
  • Re-throwing an exception
  • Multiple exceptions

Let's see the syntax:

One Catch:

try {
    // your code
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}finally {
   // this line will run definitely
}

Multiple Catch:

try {
    // your code
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}catch (TestException $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
} catch (FileException $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}finally {
   // this line will run definitely
}

You Must Read:

Example:

function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    return 1/$x;
}

try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}finally {
    echo "Done.!";
}
Top