w3resource

PHP Exception Handling: Basic usage of try-catch blocks

PHP Exception Handling: Exercise-1 with Solution

Write a PHP program that demonstrates the basic usage of try-catch blocks to handle exceptions.

Sample Solution:

PHP Code :

<?php
try {
    // Code that may throw an exception
    $numerator = 100;
    $denominator = 0;
    
    if ($denominator === 0) {
        throw new Exception("Division by zero is not allowed.");
    }
    
    $result = $numerator / $denominator;
    echo "Result: " . $result;
   } catch (Exception $e) 
   {
    // Exception handling code
    echo "An error occurred: " . $e->getMessage();
  }
?>

Sample Output:

An error occurred: Division by zero is not allowed.

Explanation:

In the above exercise, we have a division operation where the denominator is intentionally set to 0 to cause a division by zero exception. The code is wrapped inside a try block, and if an exception occurs within the try block, it is caught by the catch block. The catch block then handles the exception by displaying an error message using $e-<getMessage().

Flowchart:

Flowchart: Basic usage of try-catch blocks

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: PHP Exception Handling Exercises Home
Next: Creating and throwing custom exceptions.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/php-exercises/exception-handling/php-exception-handling-exercise-1.php