Search code examples
phpexception

What is a "catch block" in PHP?


I've been seeing code like this every now and then in PHP and I was wondering what's this all about.

$pdo = new PDO ($connect_string, $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
    $pdo->exec ("QUERY WITH SYNTAX ERROR");
} 
catch (PDOException $e) {
    echo $e->getMessage();
}

What I'm interested is the catch (PDOException $e) code in general. I var_dump the exception and it returns the PDOException class ( doh.. logical ). But that doesn't clear things what's the idea behind this technique, why it's used and what's it's name :)

I've seen this technique in Java programming also but unfortunately I don't know Java very well... :/


Solution

  • That is an exception handler to handle exceptions that have been thrown by $pdo->exec().

    When you execute $pdo->exec(), there are possible exceptions (the code not being to function as desired) that can occur, and they are thrown (with throw new PDOException('error!') or similiar). They will be thrown as far as the first catch of their specific type.

    In the example above, your catch() { ... } block will catch exceptions of PDOException. If you didn't have that block, it will bubble up to any further exception handlers, and if not handled, will crash your application. You will see some applications that have a try{ ... }/catch(){ ... } block wrapping their main request, so unhandled exceptions will bubble all the way up to it (and be handled).

    If you need to have clean up code or any code that must be ran in the event of the exception being caught, you could use finally { ... } (but PHP at this stage does not support it).

    If you want to change the behaviour of the exception handler, you can use set_exception_handler().