How to catch errors as exceptions in php?

Member

by gilbert , in category: PHP General , 10 months ago

How to catch errors as exceptions in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 6 months ago

@gilbert 

To catch errors as exceptions in PHP, you can use a combination of the try, catch, and finally blocks. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
try {
    // code that may throw an error
    $result = 1 / 0; // This will throw a DivisionByZeroError
} catch (DivisionByZeroError $e) {
    // handle the error
    echo "Division by zero error: " . $e->getMessage();
} catch (Exception $e) {
    // handle other types of errors
    echo "An error occurred: " . $e->getMessage();
} finally {
    // this block will always be executed, regardless of whether an error occurred
    echo "Finally block executed";
}


In the example above, the code inside the try block will throw a DivisionByZeroError. This error is caught by the first catch block that specifically handles DivisionByZeroError exceptions. If a different type of exception is thrown, it will be caught by the second catch block. The finally block is always executed, regardless of whether an error occurred.


You can define custom exception classes and throw them in your code using the throw statement. This allows you to create more specific error handling for different types of exceptions.