PHP Keywords: try, catch and finally
Contents
Welcome to my series on every PHP keyword and its usage. Today’s items: try
, catch
and finally
.
These keywords help your code to gracefully handle exceptions that would otherwise end its execution with an ugly error message.
The try
block includes the code that might throw an exception, while the catch
block(s) handle any exceptions thrown in the try
block.
Simple example
|
|
Multiple catch blocks
|
|
Combined catch blocks
|
|
finally
The finally
block contains code that will be executed whether or not an exception is thrown. It will be executed even if a catch
statement closes the current scope.
The finally
block is typically used to close any open connections or file pointers that would otherwise be left dangling, and to tidy up any other loose ends.
PHP does not require you to use a catch
block if you have a finally block
.
Example
|
|
Author Callum Muir
LastMod 20/02/2019