PHP Try Catch: Basics & Advanced PHP Exception Error Handling
PHP try-catch is the basic block with the feature of exception handling, that contains the code to handle exceptions. They play a crucial role in exception handling. There is one more most important keyword used with the try-catch block is throw. Therefore, the throw is a keyword that’s used to throw an exception.
Each try block must have a minimum of one catch block. on the other hand, however, a try block can also have multiple catch blocks to handle various classes of exception.
Syntax:
The given below the following syntax is used in exception handling to handle runtime errors –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php //try block try { //code that can throw exception } //catch block catch (Exception $e) { //code to print exception caught in the block } //finally block finally { //any code that will always execute } ?> |
Learn Try-Throw-Catch
- try:- The try block consists of the block of code that may contain an exception. An exception raised in the try block throughout runtime is caught by the catch block. Therefore, each try block should have a minimum of one catch block. It contains the block of code in which an exception can occur.
The following points must be noted concerning the try:
- The try block should be followed by a catch or finally block.
- A try block should have a minimum of one catch block.
- There can be multiples catch blocks with 1 (one) try block.
- throw:- It is a keyword, that is used to throw an exception. Note that one throw a minimum of has one “catch block” to catch the exception. Therefore, it lists the exceptions thrown by function, which cannot be handled by the function itself.
- catch:- The catch block catches the exception raised within the try block. It contains the code to catch the exception, that is thrown by the throw keywords within the try block. The catch block executes once a particular exception is thrown. PHP appearance for the matching catch block and assigns the exception object to a variable.
The following points to be noted concerning the catch:
- There can be used more than one catch block with a try.
- The thrown exception is caught and resolved by one or additional catches.
- The catch block can’t be used alone, it is always used with a try block.
- It comes simply once the try block.
- finally:- It is a block that always contains the essential code segment of the program to execute. The final block is additionally used for clean-up activity in PHP. it’s the same as the catch block, which is used to handle exceptions. There is the only difference is that it always executes whether an exception is handled or not.
The final block can be specified after or in place of the catch block. It always executes simply after the try & catches block whether an exception has been thrown or not, and before the normal execution restarts. it’s helpful within the following scenarios – Closing of database connection, stream.
PHP try-catch with multiple exception types
PHP supports utilize multiple catch blocks within try-catch. this permits the US to customize our code supported on the type of exception that was thrown. this is most helpful for customizing however you show an error message to a user, or if you must potentially retry something that failed the first time.
1 2 3 4 5 6 7 8 9 |
try { // run your code here } catch (Exception $e) { echo $e->getMessage(); } catch (InvalidArgumentException $e) { echo $e->getMessage(); } |
When to use PHP try-catch-finally
The finally block was else. typically in your PHP error-handling code, you may additionally wish to use a finally section. moreover, finally, it’s helpful for quite simply exception handling, it can be utilized to perform cleanup code like closing a file, closing a database connection, etc. The finally block always executes once the try-catch block exits. moreover, this ensures that the finally block is executed even if an unexpected exception occurs.
Example for try-catch-finally:
1 2 3 4 5 6 7 8 |
try { print "this is our try block n"; throw new Exception(); } catch (Exception $e) { print "something went wrong, caught yah! n"; } finally { print "this part is always executed n"; } |
The Following Below diagram showing that how the program works.
PHP Try Catch Example
Let’s see an example as given below to explain the common flow of throw and try-catch as well as finally block:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php //user-defined function with an exception function checkNumber($number) { if($number>=1) { //throw an exception throw new Exception("Value must be less than 1"); } return true; } //trigger an exception in a "try" block try { checkNumber(5); //If the exception throws, below text will not be display echo 'If you see this text, the passed value is less than 1'; } //catch exception catch (Exception $e) { echo 'Exception Message: ' .$e->getMessage(); } finally { echo '</br> It is finally block, which always executes.'; } ?> |
What is an Exception?
With PHP 5 came a new object-oriented manner of managing errors.
Exception handling is utilized to change the normal flow of the code execution if a fixed error (exceptional) condition occurs. Thus, This condition is named an exception. This is what commonly happens once an exception is triggered.
An error is an unexpected program result or an error is a surprising program output that can’t be handled by the program itself.
We can be resolved the Errors by fixing the program. An example of an error would be an infinite loop that never stops executing the program. Examples of exceptions include trying to open a file that doesn’t exist.
This exception can be handled by either creating the file or presenting the user with a choice or option of searching for the file.
Why Handle Exceptions?
Avoid unexpected results on our pages that might be terribly annoying or irritating to our end users
Improve the safety and security of our applications by not exposing information that malicious users could use to attack our applications
Purpose:- PHP Exceptions can be used to change the mainly normal flow of a program When any predictable error occurs.
PHP Error Handling
When an error occurs in the programming, then it’s only dependent on your configuration settings, PHP error message is displayed in the web browser with information relating to the error that occurred.
PHP offers several ways to handle errors.
We are going to look at the three most commonly used methods:
Die statements:– the die statements function combines with the echo and exit function in one. It is most useful when we want to output a message and stop the script execution when an error occurs.
Custom error handlers:– Custom error handlers are user-defined functions that users can call whenever an error occurs.
PHP error reporting:– the error message only depended on your PHP error reporting settings. This method is also most useful in a development environment when you have no idea what caused the error. The displayed information can help you to debug your application.