PHP exception handling: Handling specific exceptions
Write a PHP program that uses a try-catch block to handle a specific exception and performs specific actions based on the exception type.
Sample Solution:
PHP Code :
Sample Output:
CustomException: Invalid number
Explanation:
In the above exercise,
- We have a try block that contains code that throws a specific exception. We check if the $number is numeric using is_numeric() and throw a CustomException if it's not.
- The first catch block catches the CustomException specifically and handles it separately. It displays an appropriate error message using $e->getMessage() and can perform specific actions for the CustomException.
- The second catch block catches a generic Exception if another type of exception occurs. It displays an appropriate error message using $e->getMessage().
Flowchart:

PHP Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics