PHP complete se...login
PHP complete self-study manual
author:php.cn  update time:2022-04-15 13:53:54

PHP Exception



Exceptions are used to alter the normal flow of a script when a specified error occurs.


What is an exception

PHP 5 provides a new object-oriented error handling method.

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

When an exception is triggered, what typically happens is:

  • The current code state is saved

  • Code execution is switched to Predefined (custom) exception handler functions

  • Depending on the situation, the handler may restart code execution from the saved code state, terminate script execution, or start another step in the code. Continue executing the script at location

We will show different error handling methods:

  • Basic use of exceptions

  • Create a custom exception handler

  • Multiple exceptions

  • Rethrow the exception

  • Set the top-level exception handler

Note: Exceptions should only be used in error situations and should not be used to jump to a specified point Another location for the code.


Basic use of exceptions

When an exception is thrown, the subsequent code will not continue to execute, and PHP will try to find a matching "catch" code block.

If the exception is not caught and there is no need to use set_exception_handler() for corresponding processing, then a serious error (fatal error) will occur and "Uncaught Exception" (uncaught exception) will be output. wrong information.

Let's try throwing an exception without catching it:

<?php
// 创建一个有异常处理的函数
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
// 触发异常
checkNum(2);
?>
The above code will get an error like this:
Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in /www/php/test/test.php:7 Stack trace: #0 /www/php/test/test.php(13): checkNum(2) #1 {main} thrown in /www/php/test/test.php on line ;

Try, throw and catch

To avoid the error that occurred in the above example, we need to create appropriate code to handle exceptions.

Appropriate exception handling code should include:

  1. Try - Functions that use exceptions should be located within a "try" code block. If no exception is triggered, the code continues execution as usual. But if an exception is triggered, an exception will be thrown.

  2. Throw - specifies how to trigger an exception. Each "throw" must correspond to at least one "catch".

  3. Catch - The "catch" code block catches the exception and creates an object containing the exception information.

Let us 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 similar to this:
Message: 变量值必须小于等于 1

Explanation of examples:

The above code throws an exception and catches it:

  1. Create the checkNum() function. It detects whether the number is greater than 1. If so, throw an exception.

  2. Call the checkNum() function in the "try" code block.

  3. Exception in checkNum() function is thrown.

  4. The "catch" code block receives the exception and creates an object ($e) containing the exception information.

  5. Output the error message from this exception by calling $e->getMessage() from this exception object.

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


Create a custom Exception class

Creating a custom exception handler is very simple. We simply created a specialized class whose functions are called when an exception occurs in PHP. This class must be an extension of the exception class.

This custom exception class inherits all properties of PHP's exception class, and you can add custom functions to it.

We start by creating the exception class:

<?php
class customException extends Exception
{
public function errorMessage()
{
// 错误信息
$errorMsg = '错误行号 '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> 不是一个合法的 E-Mail 地址';
return $errorMsg;
}
}
$email = "someone@example...com";
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 the errorMessage() function. Just because it is a copy of the old class, it inherits properties and methods from the old class, and we can use the methods of the exception class, such as getLine(), getFile(), and getMessage().

Explanation of examples:

The above code throws an exception and catches it through a custom exception class:

  1. ## The #customException() class was created as an extension of the old exception class. This way it inherits all properties and methods of the old exception class.

  2. Create the errorMessage() function. If the e-mail address is not valid, this function returns an error message.

  3. Set the $email variable to an illegal e-mail address string.

  4. Execute the "try" code block and throw an exception because the e-mail address is illegal.

  5. The "catch" code block catches the exception and displays an error message.


Multiple exceptions

You can use multiple exceptions for a script to detect multiple situations.

You can use multiple if..else code blocks, or a switch code block, 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 = "someone@example.com";
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();
}
?>

Explanation of examples:

The above code tests two conditions. If any of the conditions is not true, an exception is thrown:

  1. customException() class Created as an extension of the old exception class. This way it inherits all properties and methods of the old exception class.

  2. Create the errorMessage() function. If the e-mail address is not valid, this function returns an error message.

  3. Set the $email variable to a string that is a valid e-mail address but contains the string "example".

  4. Execute the "try" code block, and no exception will be thrown under the first condition.

  5. Since the e-mail contains the string "example", the second condition will trigger an exception.

  6. The "catch" block catches the exception and displays the appropriate error message.

If the customException class throws an exception, but does not catch the customException, but only catches the base exception, handle the exception there.


Rethrow Exceptions

Sometimes, when an exception is thrown, you may want to handle it differently than the standard way. The exception can be thrown again in a "catch" block.

The script should hide system errors from the user. System errors may be important to programmers, but users are not interested in them. To make it easier for users, you can throw the exception again with a user-friendly message:

<?php
class customException extends Exception
{
public function errorMessage()
{
// 错误信息
$errorMsg = $this->getMessage().' 不是一个合法的 E-Mail 地址。';
return $errorMsg;
}
}
$email = "someone@example.com";
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();
}
?>

Example explanation:

The above code detects whether the email address contains the string "example". If so, the exception is thrown again:

  1. The customException() class was created as an extension of the old exception class. This way it inherits all properties and methods of the old exception class.

  2. Create the errorMessage() function. If the e-mail address is not valid, this function returns an error message.

  3. Set the $email variable to a string that is a valid e-mail address but contains the string "example".

  4. The "try" block contains another "try" block so that the exception can be thrown again.

  5. Because the e-mail contains the string "example", the exception is triggered.

  6. The "catch" code block catches the exception and rethrows "customException".

  7. Caught "customException" and displayed an error message.

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


Set the top-level exception handler

The set_exception_handler() function can set a user-defined function that handles all uncaught exceptions.

<?php
function myException($exception)
{
echo "<b>Exception:</b> " , $exception->getMessage();
}
set_exception_handler('myException');
throw new Exception('Uncaught Exception occurred');
?>
The output of the above code is as follows:
Exception: Uncaught Exception occurred
In the above code, there is no "catch" code block, but the top-level exception handler is triggered. This function should be used to catch all uncaught exceptions.

Exception rules

  • Code that requires exception handling should be placed in a try code block to catch potential exceptions.

  • Every try or throw block must have at least one corresponding catch block.

  • Use multiple catch code blocks to catch different kinds of exceptions.

  • Exceptions can be thrown (thrown again) in a catch block within a try block.

In short: if an exception is thrown, you must catch it.