PHP try catch | Error Handling
Php 14-Sep-2021

PHP try catch | Error Handling

In this tutorial, you will learn about PHP try...catch and using it on how to handle errors in PHP script.

Sometimes, you are developing any web using PHP or any php frameworks. That time no matter how much you experience in programming languages.

Because while developing the web application, some error remains by mistake. Usually, at that time PHP script execution halt, If you will use try...catch  statement in your PHP script, so this will help you to print errors.

PHP try throw catch 

The try…catch statement is used to handle errors in the PHP script.

The following syntax represents the  try...catch statement:

<?php
     
try {
    //code goes here that could lead to an exception
}
catch (Exception $e) {
    //exception handling code goes here
}
     
?>

Here,

  1. First, the code in try {...} is executed.
  2. If not come to errors in the php script, then catch(err) is ignored: the execution arrives at the finish of try and goes on, skipping catch.
  3. If an error occurs, try execution is stopped and jumps to the catch block.
  4. Each “throw” must have at least one “catch”
  5. If you want to see what error happened, you can access an error object and display errors inside a catch block.

So far, you have seen the above given syntax of try...catch .

In case the exception is thrown, the PHP script execution will be halt, and PHP will try to find the matching “catch” block.

If you do not use try catch then a fatal error will be issued with an “Uncaught Exception” message in your php script.

See the following example:

<?php
//create function with an exception
function checkAge($number) {
  if($number>18) {
    throw new Exception("You are allow here...");
  }
  return true;
}
 
//trigger exception
checkAge(21);
?>

Output

Fatal error: Uncaught exception 'Exception'
with message 'Not allow' in C:\xampp\test.php:6
Stack trace: #0 C:\xampp\test.php(12):
checkAge(16) #1 {main} thrown in C:\xampp\test.php on line 6

In this post, we mention above, try catch statement is used to handle errors in php script.

So to ignore the error from the example above, you need use try catch in your php script to handle an exception.

See the following example:

<?php
//create function with an exception
function checkAge($number) {
  if($number>18) {
    throw new Exception("You are allow here...");
  }
  return true;
}
 
//trigger exception in a "try" block
try {
  checkAge(21);
  //If the exception is thrown, this text will not be shown
  echo 'If the exception is thrown, this text will not be shown';
}catch(Exception $e) { //catch exception
  echo 'Message: ' .$e->getMessage();
}
?>

Output

Message: You are allow here...

Here,

  1. The checkAge() function is created, which is checks age is greater than 18 or not. If it is, an exception is thrown
  2. The checkAge() function is called in a “try” block
  3. The exception within the checkAge() function is thrown
  4. The “catch” block retrieves the exception and creates an object ($e) containing the exception information
  5. Echo the error message from the exception by calling $e->getMessage() from the object, containing data on exceptions.

Note that, In this example $e->getMessage function is used to get error message.

There are the following functions similar to getMessage(), which can be used from Exception class.

  • getMessage() − message of exception
  • getCode() − code of exception
  • getFile() − source filename
  • getLine() − source line
  • getTrace() − n array of the backtrace()
  • getTraceAsString() − formated string of trace

Custom Exception Class

If you want to make a custom exception handler, you can be done. But first of all, you need to create a class, containing functions proposed for handling exceptions in PHP once they are triggered.

The following example represents how to create custom exception class:

<?php
  class customException extends Exception {
    public function error_message() {
      //defining the error message
      $error_msg = 'Error caught on line '.$this->getLine().' in '.$this->getFile()
        .': <b>'.$this->getMessage().'</b> is no valid E-Mail address';
      return $error_msg;
    }
  }
 
  $email = "someonesomeone@example...com";
 
  try {
    //checking if
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
      //throwing an exception in case email is not valid
      throw new customException($email);
    }
  } catch (customException $e) {
    //displaying a custom message
    echo $e->error_message();
  }
?>

Inside the custom error_message() function, use some function contained in a normal exception class, such as GetLine()GetFile()GetMessage().

Here,

  • The customException class is extended each property and method from the Exception class.
  • This error_message() function returns an error message.
  • filter_var() function is valid e-mail address.
  • An exception is thrown, and only try() block run.
  • The main job of catch() shows an error message.

Handling Multiple Exceptions

If a piece of code can throw different types of exceptions and based on the type of multiple test conditions in the PHP script, at that time multiple exceptions occur. Keep in mind that each of these exceptions may use its own class and display their error messages.

The following example represents multiple exceptions:

<?php
  class customException extends Exception {
    public function error_message() {
      //error message
      $error_msg = 'Error caught on line '.$this->getLine().' in '.$this->getFile()
        .': <b>'.$this->getMessage().'</b> is no valid E-Mail address';
      return $error_msg;
    }
  }
 
  $email = "someonesomeone@example.com";
 
  try {
    //check if
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
      //throwing an exception in case email is not valid
      throw new customException($email);
    }
    //checking for "example" in mail address
    if(strpos($email, "example") !== FALSE) {
      throw new Exception("$email contains'example'");
    }
  }
  catch (customException $e) {
    echo $e->error_message();
  }
  catch(Exception $e) {
    echo $e->getMessage();
  }
?>

Here,

  • The customException() class is extended each property and method from the exception class.
  • The error_message()  function returns an error message.
  • filter_var() function is valid e-mail address.
  • An exception isn’t thrown, only run the try block code.
  • On checking the second condition, an exception is thrown, since the $email variable contains the example string value.
  • The main job of catch() shows an error message.

Conclusion

In this tutorial, you have learned how to handle exceptions using try()catch() and throw() functions in php script.