PHP - try...catch block

Introduction

Your code can throw exceptions.

Consider the following code:

public function setId($id) { 
    if ($id < 0) { 
        throw new Exception('Id cannot be negative.'); 
    } 
    ...
 } 

Here, exceptions are objects of the class exception.

The constructor of the Exception class takes some optional arguments, the first one of them being the message of the exception.

To handle your exception, use the try...catch blocks.

You insert the code that might throw an exception in the try block.

If an exception happens, PHP will jump to the catch block.

public function setId(int $id) { 
    try { 
        if ($id < 0) { 
            throw new Exception('Id cannot be negative.'); 
        } 
        ...
    } catch (Exception $e) { 
        echo $e->getMessage(); 
    } 
 } 

After the exception is thrown, nothing else inside the try block is executed; PHP goes straight to the catch block.

The catch block gets an argument, which is the exception thrown.