PHP programming language provides try
and catch
statements in order to manage exceptions. The exceptin
means an unexpected situation for an application that prevents the execution of the statements and interrupts the execution with errors. The try statement block is used to check any exception and the catch statement block is used to execute code if there is an error in the try statement block. There are also statements like throw
in order to create an exception manually and the finally
statement to execute code which is expected to be exception free.
try…catch Syntax
The try…catch statement has the following syntax where the try statement block is used to set code to watch for exceptions. The catch statement is used to run code if there is an exception in the try statement block. Generally, the catch statement is used with an exception variable and an exception type. We can specify exceptions in a generic way or a more specific way like file-related exceptions. The try…exception block is like the one below.
try {
CODE_BLOCK
}
catch(exception $e){
CODE_BLOCK_EXCEPTION
}
- CODE_BLOCK is the regular code block related to the application execution. Not all code in an application should be inside the try statement block. Just a suspicious part of the application code can be put inside the try statement block.
- CODE_BLOCK_EXCEPTION is executed when the related try statement raises an exception. This part is mainly related to executing some cleaning tasks about the exception like releasing resources and creating a log or notification about the exception.
Catch/Handle Exceptions
We can handle exceptions for the following sample code by using the try-and-catch statements.
try {
$result = 0/0;
} catch (Exception $e){
print "There is an exception named $e";
}
Execute Code Even Exception
The finally statement is used to execute the code even if there is an exception. We can put the code we want to execute even if there is an exception into the try statement block. But in order to work this properly the finally statement block should be an exception and reliable to prevent other exceptions.
try {
$result = 0/0;
}
catch (Exception $e){
print "There is an exception named $e";
}
finally{
print "This line is executed even there is an exception or not.";
}