Home >Backend Development >PHP Tutorial >Can PHP functions use exception handling? How to throw and catch exceptions?
PHP functions handle runtime errors and exceptions by throwing (throw) and catching (catch) exceptions: use the throw keyword to throw an exception object containing error or exception information. Catching exceptions using a try-catch statement: A try block contains code that may throw an exception. The catch block is used to handle thrown exceptions.
PHP functions throw and catch exceptions
Introduction
In PHP, functions can Handle runtime errors and exceptions through exception handling mechanisms. By throwing and catching exceptions, you can improve the maintainability and robustness of your code.
Throw an exception
You can use the throw
keyword to throw an exception. An exception is a Throwable
object or a subclass thereof that contains information about an error or exception. The syntax for throwing exceptions is as follows:
throw new Exception("Error message");
Catch exceptions
Exceptions can be caught using the try-catch
statement. The try
block contains code that may throw an exception, while the catch
block is used to handle exceptions that have been thrown. The syntax for catching exceptions is as follows:
try { // 代码可能引发异常 } catch (Exception $e) { // 处理异常 }
Practical case
Consider a function divide()
, which calculates the quotient of two numbers. If the denominator is 0, the function should throw an InvalidArgumentException
exception.
function divide($numerator, $denominator) { if ($denominator == 0) { throw new InvalidArgumentException("Dividing by zero is not allowed."); } return $numerator / $denominator; }
In the following code block, we call the divide()
function and handle the exception in the catch
block:
try { $result = divide(10, 2); echo "Result: $result"; } catch (InvalidArgumentException $e) { echo "Error: " . $e->getMessage(); }
Execute the code will output:
Result: 5
But when $denominator
is set to 0, the code will throw an InvalidArgumentException
exception and output the following:
Error: Dividing by zero is not allowed.
Notes
catch
blocks to handle different types of exceptions. finally
block to execute code regardless of whether an exception is thrown. The above is the detailed content of Can PHP functions use exception handling? How to throw and catch exceptions?. For more information, please follow other related articles on the PHP Chinese website!