0
0
PHPprogramming~5 mins

Error vs Exception in PHP

Choose your learning style9 modes available
Introduction

Errors and exceptions help PHP tell you when something goes wrong in your code. They let you find and fix problems easily.

When you want to handle unexpected problems in your PHP code without stopping the whole program.
When you want to catch mistakes like missing files or wrong input and show friendly messages.
When you want to separate serious problems (errors) from recoverable ones (exceptions).
When debugging your code to understand why it failed.
When writing code that needs to keep running even if some parts fail.
Syntax
PHP
<?php
// Throwing an exception
throw new Exception('Something went wrong');

// Catching an exception
try {
    // code that may cause exception
} catch (Exception $e) {
    echo $e->getMessage();
}

// Triggering an error
trigger_error('This is an error', E_USER_ERROR);

Exceptions are objects you can throw and catch to handle problems gracefully.

Errors are usually serious problems that stop the script unless handled.

Examples
This code throws an exception and catches it to print a message instead of stopping.
PHP
<?php
// Example of throwing and catching an exception
try {
    throw new Exception('Oops!');
} catch (Exception $e) {
    echo 'Caught exception: ' . $e->getMessage();
}
This code triggers a warning error that PHP will show but does not stop the script.
PHP
<?php
// Example of triggering an error
trigger_error('Custom error happened', E_USER_WARNING);
This code sets a custom error handler to catch errors and print a message.
PHP
<?php
// Handling errors with set_error_handler
set_error_handler(function($errno, $errstr) {
    echo "Error caught: $errstr";
});
trigger_error('Fatal error example', E_USER_ERROR);
Sample Program

This program shows how exceptions stop wrong operations like dividing by zero and how errors can warn without stopping.

PHP
<?php
function divide($a, $b) {
    if ($b == 0) {
        throw new Exception('Division by zero');
    }
    return $a / $b;
}

try {
    echo divide(10, 2) . "\n"; // Works fine
    echo divide(5, 0) . "\n";  // Throws exception
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage() . "\n";
}

// Trigger an error
trigger_error('This is a user warning', E_USER_WARNING);
OutputSuccess
Important Notes

Exceptions let you control what happens when something goes wrong.

Errors are often more serious and may stop your script unless handled.

Use try-catch blocks to handle exceptions and set_error_handler for errors.

Summary

Errors and exceptions both show problems in PHP but work differently.

Exceptions can be caught and handled to keep your program running.

Errors usually indicate serious issues but can be managed with custom handlers.