PHP Exceptions
An exception is a special type error handling method, There are it uses object-orient method to perform these actions.
Like other programming languages which are based on OOP concepts, PHP also supports try, throw & catch exception’s code block.
Let’s you have been executed a program, which is using exception handling. When program is failed at a point then It will throw an error messages out of the program.
Understand exception through an example:
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// Continue execution
echo "Hello World\n";
?>
Output:
0.2
Caught exception: Division by zero.
Hello World
Try
The try keyword initiates a code block to caught an exception in-side of this code block.
Throw
The throw keyword is used to throw an exception error to catch block, which will be produce this exception error out of the program.
Catch
The catch block is used to call exception class to raise exception messages, which is caught by exception handler.
Catch also calls different types of exception classes.
Finally
In PHP 5.5, The finally keyword is used to raise final execution within regardless multiple exception handling using. This executes always after or instead of catch block.
An example of exception with finally keyword:
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}
try {
echo inverse(5) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "First finally.\n";
}
try {
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "Second finally.\n";
}
// Continue execution
echo "Hello World\n";
?>
Output:
0.2
First finally.
Caught exception: Division by zero.
Second finally.
Hello World
How to handle nested exception
<?php
class MyException extends Exception { }
class Test {
public function testing() {
try {
try {
throw new MyException('foo!');
} catch (MyException $e) {
// rethrow it
throw $e;
}
} catch (Exception $e) {
var_dump($e->getMessage());
}
}
}
$foo = new Test;
$foo->testing();
?>
Output: