Latest web development tutorials

PHP exception handling

Exception for changing the script error occurs when the specified normal flow.


What is abnormal

PHP 5 offers a new method for error handling object-oriented.

Exception handling is used when the specified error (exception) occurs to change the normal flow of the script. This condition is called an exception.

When an exception is triggered, usually it occurs:

  • Current code state is saved
  • Code execution is switched to a pre-defined (custom) exception handler function
  • In some cases, the processor may be re-started from the code stored in the status code, terminate the script execution or continue the script from a different location code

We will show different error handling methods:

  • Basic use exception
  • Creating a custom exception handler
  • Multiple exceptions
  • Rethrows
  • Top-level exception handler set

Note: Exceptions should only use in case of error, it should not be used in a specified point to jump to another location in the code.


Basic use exception

When an exception is thrown, the subsequent code does not proceed, PHP will try to find the matching "catch" block.

If an exception is not caught, but not any with the use of set_exception_handler () for the corresponding treatment, then a serious error (Fatal error) occurs, and the output "Uncaught Exception" (uncaught exception) error messages.

Let's try to throw an exception, but do not catch it:

<?php
// 创建一个有异常处理的函数
function checkNum($number)
{
	if($number>1)
	{
		throw new Exception("Value must be 1 or below");
	}
	return true;
}

// 触发异常
checkNum(2);
?>

The code above will get an error similar to this:

Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in /www/w3big/test/test.php:7 Stack trace: #0 /www/w3big/test/test.php(13): checkNum(2) #1 {main} thrown in /www/w3big/test/test.php on line 7

Try, throw and catch

To avoid errors appearing in the above example, we need to create the appropriate code to handle exceptions.

Proper handling exception code should include:

  1. Try - using abnormal function should be located within the "try" block. If no exception is triggered, the code will continue as usual. However, if an exception is triggered, it will throw an exception.
  2. Throw - in how to trigger the exception provisions. Each "throw" must correspond to at least one "catch".
  3. Catch - "catch" block catches the exception and creates an object containing the exception message.

Let trigger an exception:

<?php
// 创建一个有异常处理的函数
function checkNum($number)
{
	if($number>1)
	{
		throw new Exception("变量值必须小于等于 1");
	}
		return true;
}
	
// 在 try 块 触发异常
try
{
	checkNum(2);
	// 如果抛出异常,以下文本不会输出
	echo '如果输出该内容,说明 $number 变量';
}
// 捕获异常
catch(Exception $e)
{
	echo 'Message: ' .$e->getMessage();
}
?>

The above code will get an error like this:

Message: 变量值必须小于等于 1

Examples explain:

The code above throws an exception and catches it:

  1. Create checkNum () function. It detects whether a number is greater than one. If it is, an exception is thrown.
  2. Call checkNum () function in a "try" block.
  3. checkNum () function exception is thrown.
  4. "Catch" block receives the exception and creates an object that contains information about the exception ($ e).
  5. By calling $ e- from this exception objects> getMessage (), the output from the error message for the exception.

However, in order to follow the "every throw must correspond to a catch" principle, you can set up a top-level exception handler to handle errors missed.


Create a custom Exception class

Creating a custom exception handler is very simple. We simply create a special class, when an exception occurs in PHP, you can call its functions. The class must be an extension of the exception class.

The custom exception class inherits all the attributes defined in the PHP exception class, you may want to add custom functions.

Start by creating exception classes:

<?php
class customException extends Exception
{
	public function errorMessage()
	{
		// 错误信息
		$errorMsg = '错误行号 '.$this->getLine().' in '.$this->getFile()
		.': <b>'.$this->getMessage().'</b> 不是一个合法的 E-Mail 地址';
		return $errorMsg;
	}
}

$email = "[email protected]";

try
{
	// 检测邮箱
	if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
	{
		// 如果是个不合法的邮箱地址,抛出异常
		throw new customException($email);
	}
}

catch (customException $e)
{
//display custom message
echo $e->errorMessage();
}
?>

This new class is a copy of the old exception class, plus errorMessage () function. Because it is a copy of the old class, so it inherits from the old class properties and methods, we can use the exception class methods, such as getLine (), getFile () and getMessage ().

Examples explain:

The code above throws an exception, and through a custom exception class to capture it:

  1. customException () class as an extension of the old exception class to create. So that it inherits all the attributes and methods of the old exception class.
  2. Create errorMessage () function. If the e-mail address is invalid, the function returns an error message.
  3. The $ email variable is set to invalid e-mail address string.
  4. The implementation of "try" block, since the e-mail address is not valid, and therefore throws an exception.
  5. "Catch" block to catch the exception and displays an error message.

Multiple exceptions

You can use multiple exceptions as a script to detect a variety of situations.

You can use multiple if..else block, or a block of code switch, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages:

<?php
class customException extends Exception
{
	public function errorMessage()
	{
		// 错误信息
		$errorMsg = '错误行号 '.$this->getLine().' in '.$this->getFile()
		.': <b>'.$this->getMessage().'</b> 不是一个合法的 E-Mail 地址';
		return $errorMsg;
	}
}

$email = "[email protected]";

try
{
	// 检测邮箱
	if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
	{
		// 如果是个不合法的邮箱地址,抛出异常
		throw new customException($email);
	}
	// 检测 "example" 是否在邮箱地址中
	if(strpos($email, "example") !== FALSE)
	{
		throw new Exception("$email 是 example 邮箱");
	}
}
catch (customException $e)
{
	echo $e->errorMessage();
}
catch(Exception $e)
{
	echo $e->getMessage();
}
?>

Examples explain:

The code above tests two conditions, if any one condition is not satisfied, then throw an exception:

  1. customException () class as an extension of the old exception class to create. So that it inherits all the attributes and methods of the old exception class.
  2. Create errorMessage () function. If the e-mail address is invalid, the function returns an error message.
  3. The $ email variable is set to a string that is a valid e-mail address, but contains the string "example".
  4. The implementation of "try" block of code in the first condition, no exception is thrown.
  5. Since the e-mail contains the string "example", the second condition triggers an exception.
  6. "Catch" block catches the exception and display the appropriate error message.

If customException class exception is thrown but not caught customException, captured only a base exception, where the handle exceptions.


Rethrows

Sometimes, when an exception is thrown, you may wish to differ from the standard way to handle it. May again be thrown in a "catch" block.

The script should be hidden from the user system errors. For programmers, system errors may be important, but the user is not interested in them. To make it easier for users to use, you can throw an exception again with relatively user-friendly message:

<?php
class customException extends Exception
{
	public function errorMessage()
	{
		// 错误信息
		$errorMsg = $this->getMessage().' 不是一个合法的 E-Mail 地址。';
		return $errorMsg;
	}
}

$email = "[email protected]";

try
{
	try
	{
		// 检测 "example" 是否在邮箱地址中
		if(strpos($email, "example") !== FALSE)
		{
			// 如果是个不合法的邮箱地址,抛出异常
			throw new Exception($email);
		}
	}
	catch(Exception $e)
	{
		// 重新抛出异常
		throw new customException($email);
	}
}
catch (customException $e)
{
	// 显示自定义信息
	echo $e->errorMessage();
}
?>

Examples explain:

The above code is detected in the e-mail address if it contains the string "example". If there is, again, an exception is thrown:

  1. customException () class as an extension of the old exception class to create. So that it inherits all the attributes and methods of the old exception class.
  2. Create errorMessage () function. If the e-mail address is invalid, the function returns an error message.
  3. The $ email variable is set to a string that is a valid e-mail address, but contains the string "example".
  4. "Try" block contains another "try" block of code, so you can throw an exception again.
  5. Since the e-mail contains the string "example", and therefore trigger an exception.
  6. "Catch" block to catch the exception and re-throw "customException".
  7. Captured "customException", and displays an error message.

If an exception is not caught in the current "try" block, it looks for the catch block at a higher level.


Top-level exception handler set

set_exception_handler () function can be set to handle all uncaught exception of user-defined functions.

<?php
function myException($exception)
{
	echo "<b>Exception:</b> " , $exception->getMessage();
}

set_exception_handler('myException');

throw new Exception('Uncaught Exception occurred');
?>

The output of the code above is as follows:

Exception: Uncaught Exception occurred

In the above code, there is no "catch" block, but the top-level exception handler triggered. This function should be used to capture all uncaught exception.


Exception rule

  • Exception handling code needs to be placed in a try block, in order to catch potential exceptions.
  • Each throw or try code block must have at least one corresponding catch block.
  • You can use multiple catch blocks to catch different types of exceptions.
  • May be within the try code block throws catch block (again thrown) exception.

In short: If you throw an exception, you must catch it.