PHP - Catching different types of exceptions

Introduction

The following code shows how to catch multiple exceptions.

try { 
    echo "\nTrying to create a new customer with id $id.\n"; 
    return new Basic($id, "name", "surname", "email"); 
} catch (InvalidIdException $e) { 
    echo "You cannot provide a negative id.\n"; 
} catch (ExceededMaxAllowedException $e) { 
    echo "No more customers are allowed.\n"; 
} catch (Exception $e) { 
    echo "Unknown exception: " . $e->getMessage(); 
} 

Here, we catch three exceptions here: two new exceptions and the generic one.

PHP tries to use the catch blocks in the order that you defined them.

If your first catch is for Exception, the rest of the blocks will be never executed, as all exceptions extend from that class.

     try { 
        echo "\nTrying to create a new customer with id $id.\n"; 
        return new Basic($id, "name", "surname", "email"); 
     } catch (Exception $e) { 
        echo 'Unknown exception: ' . $e->getMessage() . "\n"; 
     } catch (InvalidIdException $e) { 
        echo "You cannot provide a negative id.\n"; 
     } catch (ExceededMaxAllowedException $e) { 
        echo "No more customers are allowed.\n"; 
     } 

The result that you get from the browser will always be from the first catch.

Related Topic