How to handle exceptions

The syntax for a try/catch statement

       try {
         // statements that might throw an exception
       } catch (ExceptionClass $exception_name) {
         // statements that handle the exception
       }
      

The syntax for executing a method of any object

      $objectName->methodName(argumentList);
      

How to handle a PDO exception

      try { 
        $db = new PDO($dsn, $username, $password);
        echo("You are connected to the database!</p>\n");
      } catch (PDOException $e) {
        $error_message = $e->getMessage();
        echo("<p>An error occurred while connecting to the database: $error_message&;t'/p>");
        exit;
      }
      

How to handle any type of exception

      try {
        // statements that might throw an exception
      } catch (Exception $e) {
        $error_message = $e->getMessage(); 
        echo(<p>An error occurred while connecting to the database: $error_message);
        exit;
      }
      

Description

Back