Source Code:
(back to article)
<?php // Example 1 function divide($a, $b) { try { if ($b == 0) { throw new Exception("Division by zero."); } return $a / $b; } catch (Exception $e) { echo "Error: " . $e->getMessage(); } finally { echo "This code will always be executed."; } } divide(10, 0); // Output: Error: Division by zero.This code will always be executed. // Example 2 $file = "example.txt"; $handle = fopen($file, "r"); try { if (!$handle) { throw new Exception("Unable to open file."); } // code to be executed } catch (Exception $e) { echo "Error: " . $e->getMessage(); } finally { fclose($handle); } // Output: Error: Unable to open file.
Result:
Report an issue