w3resource

PHP Exception Handling: Try-Catch blocks for error messages

PHP Exception Handling: Exercise-4 with Solution

Write a PHP script that uses try-catch blocks to handle different types of exceptions and display appropriate error messages.

Sample Solution:

PHP Code :

<?php
try {
    // Code that may throw different types of exceptions
    $file = "test.txt";
    
    if (!file_exists($file)) {
        throw new RuntimeException("File does not exist.");
    }
    
    $handle = fopen($file, "r");
    if (!$handle) {
        throw new Exception("Error opening file.");
    }
    
    // Perform some file operations
    // ...
    
    fclose($handle);
} catch (RuntimeException $e) {
    // Handle RuntimeException
    echo "RuntimeException: " . $e->getMessage();
} catch (Exception $e) {
    // Handle generic Exception
    echo "Exception: " . $e->getMessage();
} finally {
    // Clean up resources or perform final actions
    echo "Script execution completed.";
}
?>

Sample Output:

RuntimeException: File does not exist.Script execution completed.

Explanation:

In the above exercise,

  • We have a try block that contains code that throws different types of exceptions. We first check if a file exists using the file_exists() function and throw a RuntimeException if the file doesn't exist. Then, we try to open the file using fopen() and throw a generic Exception if the file opening fails.
  • The catch blocks catch specific exception types (RuntimeException and Exception) and handle them separately. We display appropriate error messages using $e->getMessage().
  • Finally, the finally block is optional and allows you to clean up resources or perform final actions. In this example, we simply display a message indicating script execution completion.

Flowchart:

Flowchart: Try-Catch blocks for error messages

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Divide with zero denominator check.
Next: Custom exception for missing file.

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://w3resource.com/php-exercises/exception-handling/php-exception-handling-exercise-4.php