PHP Exception Handling

PHP  Exception handling is nearly identical to that of other programming languages. Before moving ahead let’s see what exception is:

For exception handling, PHP supports the following keywords.

KeywordsDescription
tryIt specifies a piece of code where an exception may occur.
catchIt specifies a piece of code that will be executed in case of a particular exception.
throwIt is used to throw a warning. It’s also used to keep track of the exceptions that a function raises but doesn’t resolve.
finallyIt is used instead of or after a catch block in PHP code, and it is primarily used for cleanup.

Throwing an Exception

It is used to throw a warning. It’s also used to keep track of the exceptions that a function raises but doesn’t resolve. When an exception is thrown, the code that follows it is not executed.

A fatal error with an “Uncaught Exception” warning will occur if an exception is not caught.

Let’s see if we can throw an exception without being caught:

<?php
function div($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero");
  }
  return $dividend / $divisor;
}

echo div(10, 0);
?>

As in the above example, we have just thrown the exception but not catch it so it will give an error(Uncaught Exception).

The try…catch Statement

We can use the try…catch statement to catch exceptions and continue the procedure, avoiding the error from the previous example.

Syntax:

try {
  code that is likely to throw exception
} catch(Exception $e) {
  When an exception is thrown, code is executed.
}
<?php
function div($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero");
  }
  return $dividend / $divisor;
}

try {
  echo div(10, 0);
} catch(Exception $e) {
  echo "Cannot divide because divisor is 0.";
}
?>

The try…catch…finally Statement

Exceptions can be caught using the try…catch…finally statement. Regardless of whether an exception was caught, code in the “finally” block will always run. 

Syntax

try {
  code that is likely to throw exception
} catch(Exception $e) {
 When an exception is thrown, code is executed.
} finally {
  Code that will run in any case
}
<?php
function div($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero");
  }
  return $dividend / $divisor;
}

try {
  echo div(10, 0);
} catch(Exception $e) {
  echo "Cannot divide because divisor is 0.";
}
finally{
  echo "You may further proceed";
}
?>

Exception Object and Methods

The Exception object holds information about the error or unexpected issues experienced by the function.

There are three parameters exception method can hold and all are optional, Let’s see below:

new Exception(message, code, previous)
ParameterDescription
messageAn explanation of why the exception was thrown.
codeAn integer that can be used to tell this exception apart from others of the same type.
previousIt is suggested to pass this exception into this argument if it was thrown in a catch block of another exception.

Methods

The table below shows some of the methods that can be used to retrieve information about an exception when catching it:

MethodDescription
getMessage()Returns a string specifying the reason for the exception.
getCode()It returns the exception code.
getFile()The entire path to the file where the exception was thrown is returned.
getLine()The number of lines of the code that threw the exception is returned.
getPrevious()This method returns the previous exception if this one was triggered by another. If it doesn’t, it returns null.
<?php
function div($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero", 1);
  }
  return $dividend / $divisor;
}

try {
  echo div(10, 0);
} catch(Exception $e) {
  $code = $e->getCode();
  $line = $e->getLine();
  $msg = $e->getMessage();
  $file = $e->getFile();
  echo "Exception thrown in $file on line $line: [Code $code]
  $msg";
}
?>