PHP Exceptions

In PHP, exceptions are used to handle errors and other exceptional events in a structured and maintainable way. They provide a way to transfer control from one part of a program to another using try, catch, and throw blocks.


Basic Syntax of PHP Exceptions

try { // Code that may throw an exception if (!$file = fopen("somefile.txt", "r")) { throw new Exception("File not found."); } } catch (Exception $e) { // Handle exception echo "Caught exception: " . $e->getMessage(); } finally { // Optional block that always executes echo "Cleaning up..."; }

Key Keywords

Keyword Description
try Block of code where exceptions might occur
catch Block to handle the exception
throw Used to throw an exception
finally Optional; always runs, even after a return or exception

Custom Exception Class

You can create your own exception classes by extending the built-in Exception class:

class MyCustomException extends Exception {} try { throw new MyCustomException("Something custom went wrong!"); } catch (MyCustomException $e) { echo $e->getMessage(); }

Useful Exception Methods

  • $e->getMessage() – Gets the exception message

  • $e->getCode() – Gets the exception code

  • $e->getFile() – Gets the file in which the exception occurred

  • $e->getLine() – Gets the line number of the error

  • $e->getTrace() – Gets the stack trace as an array

  • $e->getTraceAsString() – Gets the stack trace as a string


Best Practices

  • Use exceptions for exceptional situations, not regular control flow.

  • Always catch exceptions where you can handle them meaningfully.

  • Avoid suppressing exceptions unless absolutely necessary.