Exception handling in PHP, is used to deal with runtime errors, these runtime errors are called exception. These error crash the program or terminates the PHP script abnormally. During runtime errors, to execute program normally, PHP provides following exception handling functions.
try
The code should be placed in try block, where runtime error may occur. If error occurs, because of try block program will not crash. program execution control is transferred to catch block to handle the exception and program executes completely.
Syntax
try{
// set of statements
}
catch
Catch block deals with exception when error(Exception) occurs in try block. Multiple catch block can be used with try block.
Syntax
catch(Exception variable){
// set of statements
}
Either try block executes or catch block, means if try executes successfully than catch will not execute and vice versa.
finally
finally block always executes, it is optional.
Syntax
finally{
// set of statements
}
There must be at least one catch block or finally block or both with try block.
Syntax
try{
// set of statements
}catch(Exception variable){
// set of statements
}finally{
// set of statements
}
Example
<?php
$a = 20;
$b = 0;
$c = 0;
try{
$c = $a/$b;
}
catch(Exception $e){
echo $e->getMessage();
}
finally{
echo "Completed";
}
?>