Using finally in PHP exception handling

Опубликовано: 27 Апрель 2026
на канале: PHP Explained
169
2

The unexpected events and errors are called exceptions. Developers can handle these exceptions using try-catch blocks, so that exceptions should not stop the program and execution will be continued.

The finally is an optional block comes along with try-catch block. The code in finally block will always run regardless of whether an exception was caught.

Let's see an example.
We are trying to divide a number by 0. We throw an exception if the divisor is 0. As a result, rest of lines of code will not execute. Then exception is implemented and statement "Unable to divide." will be displayed. At the end, finally block will run and "Process complete." will be displayed.
$divident = 5;
$divisor = 0;
try {
if($divisor == 0)
{
throw new Exception("Division by zero");
}
$res = $divident / $divisor;
echo $res;
} catch(Exception $e) {
echo "Unable to divide.";
} finally {
echo "Process complete.";
}