PHP like any other programming language has an exception handling feature. You can write your code in a such way that it catches the most obvious exception depending on your programs logic. Exceptions allow you to manage errors much effectively and this is the reason you should consider using them in your program. In this tutorial we’ll take a look at how exceptions in PHP work.
Before you check out the code, let’s take a look at the three keywords related to the exceptions.
- Try – Inside the try function block we’re checking if a particular programming logic triggers an exception.
- Throw – If the program finds an exception in try block we throw an exception using throw keyword.
- Catch – This is the block where an object is created with exception information.
Check the below code to see how an exception handling program works.
<? php try { $checkvar= 'testing error'; throw new Exception($checkvar); echo 'ine is skipped by compiler as it moves directly in catch block after throwing an exception'; } catch (Exception $e) { echo 'Found an exception: ', $e->getMessage(), "\n"; } echo 'Exception program demo; ?>
In try block we’re creating a variable and throwing a new exception when compiler finds it. Any line after the throw keyword is not executed as the entire block is skipped to catch. So any code below the throw keyword is skipped. Inside catch block an exception is thrown and you get the error message printed. After this the last echo statement is printed on webpage.
Points to Remember:
- An exception can be caught or thrown with the help of php block.
- There should be atleast one catch block for corresponding try block.
- Exceptions can be thrown or rethrown within a catch block.
You can use the exception handling while working with php file handling or network connection related programs. I hope this helps you to understand the exception handling in php. If you have any questions, suggestions related to this tutorial, feel free to comment. If the comments are expired on this post, feel free to use twitter to ask me.