PHP Tutorial
PHP Flow Control
PHP Functions
PHP String
PHP Array
PHP Date Time
PHP Object Oriented
Regular Expression
PHP Cookie & Session
PHP Error & Exception handling
MySQL in PHP
PHP File Directory
PHP Image Processing
Exception handling is a key part of designing robust PHP applications. In PHP, an exception is an event that disrupts the normal flow of the program's instructions. It is used to handle errors and other exceptional events in PHP scripts. The keyword try
, catch
, and finally
are used for exception handling in PHP.
Here's a simple tutorial about exception handling in PHP:
Basic Exception Handling
The basic syntax for exception handling in PHP is as follows:
try { // Code that may throw an exception } catch (ExceptionType $variable) { // Code to handle the exception }
In the try
block, you put the code that may throw an exception. In the catch
block, you handle the exception. If an exception is thrown in the try
block, the catch
block is executed. If no exception is thrown, the catch
block is skipped.
Here is an example:
<?php try { $num = 2; if($num > 1) { throw new Exception("The number is greater than 1"); } echo "This will not be displayed"; } catch (Exception $e) { echo "Caught exception: ", $e->getMessage(), "\n"; } ?>
In this example, because the number is greater than 1, an exception is thrown, and the message "Caught exception: The number is greater than 1" is displayed.
Multiple Catch Blocks
You can have multiple catch
blocks to catch different types of exceptions. The first catch
block that matches the type of the thrown exception will be executed.
<?php try { // Some code... } catch (FirstExceptionType $e) { // Handle first type of exception } catch (SecondExceptionType $e) { // Handle second type of exception } catch (Exception $e) { // Handle all other exceptions } ?>
Finally Block
The finally
block can be added after the catch
blocks. The code in this block will be executed regardless of whether an exception was thrown and handled.
<?php try { // Some code... } catch (Exception $e) { // Handle exception } finally { // Cleanup code, always executed } ?>
Creating Custom Exceptions
You can also create custom exceptions in PHP. A custom exception class must extend PHP's built-in Exception
class or one of its descendants.
<?php class CustomException extends Exception { // Custom exception properties, methods, etc. } try { // Some code... throw new CustomException("Something went wrong"); } catch (CustomException $e) { // Handle custom exception } ?>
In this example, a custom exception type CustomException
is created by extending the Exception
class.
Remember, exceptions are used to handle situations which are out of the ordinary (hence the term "exception"). They should not be used for controlling regular application flow.
Handling exceptions with try-catch in PHP: Use try-catch blocks to handle exceptions:
<?php try { // Code that may throw an exception throw new Exception('This is an exception'); } catch (Exception $e) { // Handle the exception echo 'Caught exception: ', $e->getMessage(), "\n"; }
Handling multiple exceptions with try-catch in PHP: Handle multiple exception types in a single try-catch block:
<?php try { // Code that may throw exceptions if ($condition) { throw new InvalidArgumentException('Invalid argument'); } else { throw new RuntimeException('Runtime error'); } } catch (InvalidArgumentException $e) { echo 'Caught invalid argument exception: ', $e->getMessage(), "\n"; } catch (RuntimeException $e) { echo 'Caught runtime exception: ', $e->getMessage(), "\n"; }
Custom exception classes in PHP: Create and use custom exception classes:
<?php class CustomException extends Exception {} try { // Code that may throw a custom exception throw new CustomException('This is a custom exception'); } catch (CustomException $e) { // Handle the custom exception echo 'Caught custom exception: ', $e->getMessage(), "\n"; }
PHP catch multiple exception types: Catch multiple exception types using a single catch block:
<?php try { // Code that may throw exceptions throw new InvalidArgumentException('Invalid argument'); } catch (InvalidArgumentException | RuntimeException $e) { // Handle either InvalidArgumentException or RuntimeException echo 'Caught exception: ', $e->getMessage(), "\n"; }
PHP finally block usage in exception handling: Use the finally block for code that should be executed regardless of whether an exception is thrown or not:
<?php try { // Code that may throw an exception throw new Exception('This is an exception'); } catch (Exception $e) { // Handle the exception echo 'Caught exception: ', $e->getMessage(), "\n"; } finally { // Code to be executed regardless of whether an exception is thrown or not echo 'Finally block executed', "\n"; }
Rethrowing exceptions in PHP: Rethrow an exception after catching it:
<?php try { // Code that may throw an exception throw new Exception('This is an exception'); } catch (Exception $e) { // Handle the exception or log it echo 'Caught exception: ', $e->getMessage(), "\n"; // Rethrow the exception throw $e; }
Exception chaining in PHP: Chain exceptions to provide more context:
<?php try { // Code that may throw an exception throw new InvalidArgumentException('Invalid argument'); } catch (InvalidArgumentException $e) { // Wrap the caught exception in a new exception with additional context throw new RuntimeException('Error processing data', 0, $e); }
Using set_exception_handler() in PHP:
Set a global exception handler using set_exception_handler()
:
<?php function customExceptionHandler($e) { echo 'Custom exception handler: ', $e->getMessage(), "\n"; } set_exception_handler('customExceptionHandler'); // Code that may throw an exception throw new Exception('This is an exception');
PHP global exception handler: Create a global exception handler using a custom class:
<?php class GlobalExceptionHandler { public static function handle($e) { echo 'Global exception handler: ', $e->getMessage(), "\n"; } } set_exception_handler(['GlobalExceptionHandler', 'handle']); // Code that may throw an exception throw new Exception('This is an exception');
Logging exceptions with PHP error_log():
Log exceptions using error_log()
:
<?php try { // Code that may throw an exception throw new Exception('This is an exception'); } catch (Exception $e) { // Log the exception error_log('Caught exception: ' . $e->getMessage()); }
PHP try-catch vs if-else for error handling: Compare try-catch blocks with if-else for error handling:
<?php // Using try-catch try { // Code that may throw an exception throw new Exception('This is an exception'); } catch (Exception $e) { // Handle the exception echo 'Caught exception: ', $e->getMessage(), "\n"; } // Using if-else $result = riskyOperation(); if ($result === false) { echo 'Error occurred during operation', "\n"; }
Handling uncaught exceptions in PHP: Use a global exception handler to catch unhandled exceptions:
<?php function globalExceptionHandler($e) { echo 'Uncaught exception: ', $e->getMessage(), "\n"; } set_exception_handler('globalExceptionHandler'); // Code that may throw an exception throw new Exception('This is an uncaught exception');