In this tutorial, you shall learn how to define a custom exception in PHP, with the help of example programs.

PHP – User defined / Custom Exception

In PHP, we can create user defined exception (a class) by extending it with the built-in Exception class.

Syntax

The syntax to create a simple user defined exception MyException is given below.

</>
Copy
class MyException extends Exception { }

If required, we can define constructor and custom functions for this class.

Examples (2)

1. A simple program that defines a custom Exception

In the following program, we define a custom exception, MyException and throw this exception from try-block. We shall catch this exception in catch-block and print the exception message to output using echo statement.

PHP Program

</>
Copy
<?php
  class MyException extends Exception { }

  try {
    //some code
    throw new MyException("This is a message from MyException.");
  } catch (MyException $e) {
    //handle exception
    echo $e->getMessage();
  }
?>

Output