PHP Exceptions

⚠️ 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.


1️⃣ 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.


2️⃣ Multiple Catch Blocks (PHP 7+)

You can catch different exception types separately:


 

  • Specific exceptions should come before general Exception.


3️⃣ 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.

4️⃣ Creating Custom Exceptions

You can create your own exception class:


 

✅ Useful for application-specific errors.


5️⃣ Exception Methods

Method Description
$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:


 


6️⃣ 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.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *