Home > Article > Backend Development > What is exception handling in PHP?
Exceptions are problems that occur during program execution. During program execution, when an exception occurs, the code following the statement will not be executed and PHP will try to find the first matching catch block. If the exception is not caught, a PHP fatal error is issued with "Uncaught Exception" displayed.
try { print "this is our try block"; throw new Exception(); }catch (Exception $e) { print "something went wrong, caught yah! n"; }finally { print "this part is always executed"; }
<?php function printdata($data) { try { //If var is six then only if will be executed if($data == 6) { // If var is zero then only exception is thrown throw new Exception('Number is six.'); echo "</p><p> After throw (It will never be executed)"; } } // When Exception has been thrown by try block catch(Exception $e){ echo "</p><p> Exception Caught", $e->getMessage(); } //this block code will always executed. finally{ echo "</p><p> Final block will be always executed"; } } // Exception will not be rised here printdata(0); // Exception will be rised printdata(6); ?>
Final block will be always executed Exception CaughtNumber is six. Final block will be always executed
To To handle exceptions, program code must be located within a try block. Each attempt must have at least one corresponding catch block. Multiple catch blocks can be used to catch different categories of exceptions.
The above is the detailed content of What is exception handling in PHP?. For more information, please follow other related articles on the PHP Chinese website!