php
PHP Exceptions
PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch or finally block.

Try : A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown".

Throw : This is how you trigger an exception. Each "throw" must have at least one "catch".

Catch : A "catch" block retrieves an exception and creates an object containing the exception information.
The following example demonstrates how to work exception handling :
<!DOCTYPE html>
<html>
<head>
    <title>Exceptions Handling</title>
</head>
<body>

<?php
//create function with an exception
function checkNum($number) {
  if($number>1) {
    throw new Exception("Value must be 1 or below");
  }
  return true;
}

//trigger exception in a "try" block
try {
  checkNum(2);
  //If the exception is thrown, this text will not be shown
  echo 'If you see this, the number is 1 or below';
}

//catch exception
catch(Exception $e) {
  echo 'Message: ' .$e->getMessage();
}
?>

</body>
</html>
Output :
In the above example $e->getMessage function is used to get error message. There are following functions which can be used from Exception class.
Method Description Example
getMessage() Displays the exception’s message
<?php
  echo $e->getMessage();
?>
getCode() Displays the numeric code that represents the exception
<?php
  echo $e->getCode();
?>
getFile() Displays the file name and path where the exception occurred
<?php
  echo $e->getFile();
?>
getLine() Displays the line number where the exception occurred
<?php
  echo $e->getLine();
?>
getTrace() Displays an array of the backtrace before the exception
<?php
  print_r( $e->getTrace());
?>
getPrevious() Displays the previous exception before the current one
<?php
  echo $e->getPrevious();
?>
getTraceAsString() Displays the backtrace of the exception as a string instead of an array
<?php
  echo $e->getTraceAsString();
?>
__toString() Displays the entire exception as a string
<?php
  echo $e->__toString();
?>
Creating a Custom Exception

You can define your own custom exception handler. Use following function to set a user-defined exception handler function.

set_exception_handler ( $exception_handler )

Here exception_handler is the name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler().

<!DOCTYPE html>
<html>
<head>
    <title>Creating a Custom Exception Handler</title>
</head>
<body>

<?php
   function exception_handler($exception) {
      echo "Creating a Custom Exception : " , $exception->getMessage(), "\n";
   }
	
   set_exception_handler('exception_handler');
   throw new Exception('Creating a Custom Exception');
   
   echo "Not Executed\n";
?>

</body>
</html>
Output :
Multiple Exceptions

Multiple exception use multiple try catch blocks to handle the thrown exceptions. These exceptions can use different exception classes and return different error messages

You want to display a customized message depending on the exception thrown

You want to perform a unique operation depending on the exception thrown

We expect two types of exceptions to occur;

  • Division by zero
  • Division by a negative number

For simplicity’s sake, we will only display the exception type in our catch blocks. The PHP built in Exception class is used to throw exceptions.We will create two classes that extend the exception class and use them to throw exceptions.

The multiple exception implementation code is following :

<!DOCTYPE html>
<html>
<head>
    <title>Multiple Exceptions</title>
</head>
<body>

<?php
class DivideByZeroException extends Exception {};
class DivideByNegativeException extends Exception {};
function process($denominator)
{
	try
	{
		if ($denominator == 0)
		{
			throw new DivideByZeroException();
		}
		else if ($denominator < 0)
		{
			throw new DivideByNegativeException();
		}
		else
		{
			echo 25 / $denominator;
		}
	}
	catch (DivideByZeroException $ex)
	{
		echo "DIVIDE BY ZERO EXCEPTION!";
	}
	catch (DivideByNegativeException $ex)
	{
		echo "DIVIDE BY NEGATIVE NUMBER EXCEPTION!";
	}
	catch (Exception $x)
	{
	echo "UNKNOWN EXCEPTION!";
	}
}
process(0);
?>

</body>
</html>
Output :