The Exception Class
The Exception
class is the base class for all exceptions in PHP.
It contains basic methods for working with exceptions: getting the error message,
error code, file and line where the exception occurred, as well as the call stack.
When creating an exception, you can pass a message, error code, and previous exception.
Syntax
new Exception(string $message = "", int $code = 0, Throwable $previous = null);
Example
Let's create and handle a simple exception:
<?php
try {
throw new Exception('Something went wrong', 100);
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>
Code execution result:
'Error: Something went wrong'
Example
Let's use the main methods of the Exception class:
<?php
try {
throw new Exception('Test exception', 123);
} catch (Exception $e) {
echo 'Message: ' . $e->getMessage() . "\n";
echo 'Code: ' . $e->getCode() . "\n";
echo 'File: ' . $e->getFile() . "\n";
echo 'Line: ' . $e->getLine() . "\n";
}
?>
Code execution result (example):
'Message: Test exception
Code: 123
File: /path/to/file.php
Line: 3'
Example
Let's get the call stack for an exception:
<?php
function test() {
throw new Exception('Stack trace test');
}
try {
test();
} catch (Exception $e) {
print_r($e->getTrace());
}
?>
Code execution result (example):
[
[
'file' => '/path/to/file.php',
'line' => 5,
'function' => 'test',
'args' => []
]
]
See Also
-
the
ErrorException
class,
which represents errors as exceptions -
the
set_exception_handler
function,
which sets a custom exception handler