Exception in PHP
Exceptions in PHP
In PHP, exceptions provide a powerful way to handle errors and unusual conditions in a controlled manner. Rather than letting errors crash your program, you can catch them and decide how to respond.
? What is an Exception?
An exception is an object that describes an error or unexpected behavior in a program. It can be "thrown" and "caught" using try, catch, and throw statements.
? Basic Exception Handling Syntax
<?phptry { // Code that might throw an exception throw new Exception("Something went wrong!");} catch (Exception $e) { // Code to handle the exception echo "Caught exception: " . $e->getMessage();}?>? Explanation:
tryblock: Code that might cause an exception.throw: Used to throw an exception manually.catch: Catches and handles the thrown exception.
? Example with Division by Zero
<?phpfunction divide($a, $b) { if ($b == 0) { throw new Exception("Cannot divide by zero."); } return $a / $b;}try { echo divide(10, 0);} catch (Exception $e) { echo "Error: " . $e->getMessage();}?>Output:
Error: Cannot divide by zero.? Custom Exception Class
You can also define your own custom exception class:
<?phpclass MyException extends Exception { public function errorMessage() { return "Custom Error: " . $this->getMessage(); }}try { throw new MyException("This is a custom exception.");} catch (MyException $e) { echo $e->errorMessage();}?>? Multiple Catch Blocks (PHP 7+)
<?phptry { // code that might throw multiple types of exceptions} catch (InvalidArgumentException $e) { echo "Invalid argument: " . $e->getMessage();} catch (Exception $e) { echo "General error: " . $e->getMessage();}?>? Finally Block
The finally block executes regardless of whether an exception was thrown or not.
<?phptry { echo "Trying...<br>"; throw new Exception("Something failed!");} catch (Exception $e) { echo "Caught: " . $e->getMessage() . "<br>";} finally { echo "Always runs this.";}?>? Built-in Exception Methods
| Method | Description |
|---|---|
getMessage() | Returns the exception message. |
getCode() | Returns the exception code. |
getFile() | Returns the file in which the exception was created. |
getLine() | Returns the line number. |
getTrace() | Returns an array of the backtrace. |
getTraceAsString() | Returns the backtrace as a string. |
? Best Practices
Use exceptions for exceptional conditions (not for flow control).
Always catch exceptions to avoid unhandled fatal errors.
Log exception details for debugging.