PHP Exceptions

PHP Tutorial

PHP Exceptions Tutorial

In PHP, exceptions are used to handle runtime errors in a structured way. Exceptions allow you to catch and handle errors gracefully instead of letting the script crash.


 Basic Try-Catch


 

Output:

Caught exception: Number is greater than 5!
  • throw is used to generate an exception.
  • catch is used to handle the exception.

 Multiple Catch Blocks (PHP 7+)

You can catch different exception types separately:


 

  • Specific exceptions should come before general Exception.


 Using finally Block

The finally block executes regardless of whether an exception occurred:


 

Output:

Try block executed.
Caught exception: Something went wrong!
Finally block always executes.

 Creating Custom Exceptions

You can create your own exception class:


 

 Useful for application-specific errors.


Exception Methods

MethodDescription
$e->getMessage()Returns error message
$e->getCode()Returns exception code
$e->getFile()Returns file where exception occurred
$e->getLine()Returns line number
$e->getTrace()Returns stack trace as array
$e->getTraceAsString()Returns stack trace as string

Example:


 


 Key Points

  1. Exceptions are object-oriented error handling.

  2. Use try for risky code, catch to handle exceptions.

  3. finally executes always, even if no exception occurred.

  4. Create custom exception classes for application-specific errors.

  5. Exception methods provide detailed debugging information.

You may also like...