Home >Backend Development >PHP Tutorial >How to catch and handle custom exceptions in PHP?
Methods to capture and handle custom exceptions in PHP: Inherit the Exception class to create custom exceptions. Use the throw keyword to throw a custom exception. Use try, catch, and finally blocks to catch and handle exceptions.
How to catch and handle custom exceptions in PHP
Introduction
In PHP Handling exceptions is critical to building robust and maintainable applications. Custom exceptions allow you to create exceptions that are tailored to specific errors or unusual situations in your code. This article will guide you through how to catch and handle custom exceptions, and provide a practical case to demonstrate its usage.
Create custom exception
To create a custom exception, use the extends
keyword to inherit the built-in Exception
class and define A constructor to receive an error message and optional exception code:
class MyCustomException extends Exception { public function __construct($message, $code = 0) { parent::__construct($message, $code); } }
Throw a custom exception
When a situation in the code requires a custom exception to be thrown , please use the throw
keyword, followed by an instance of the custom exception class:
throw new MyCustomException("错误消息");
Catching and handling exceptions
Use try
, catch
and finally
blocks to catch and handle exceptions:
try { // 代码可能会抛出异常 } catch (MyCustomException $e) { // 处理 MyCustomException 异常 } catch (Exception $e) { // 处理所有其他异常 } finally { //无论是否抛出异常都会执行此块 }
Practical Case
Consider a simple mathematical function that calculates two The sum of numbers. If either number is negative, throw NegativeNumberException
Exception:
NegativeNumberException Class:
class NegativeNumberException extends MyCustomException { public function __construct($message = "不能对负数求和") { parent::__construct($message); } }
Mathematical functions:
function sum($a, $b) { if ($a < 0 || $b < 0) { throw new NegativeNumberException(); } return $a + $b; }
Usage:
try { $result = sum(-1, 2); } catch (NegativeNumberException $e) { echo $e->getMessage(); } catch (Exception $e) { echo $e->getMessage(); }
Output:
不能对负数求和
Conclusion
In PHP Catching and handling custom exceptions is critical to building robust and reliable applications. By inheriting the Exception
class and using the try
, catch
, and finally
blocks, you can create an error handling strategy that is specific to your code.
The above is the detailed content of How to catch and handle custom exceptions in PHP?. For more information, please follow other related articles on the PHP Chinese website!