Rethrowing exceptions

Rethrowing exceptions is a relatively common practice in development. Sometimes, we wish to catch an exception, look into it, do a bit of an extra logic, and then rethrow the exception back so that the parent catch block might handle it further.

Let's take a look at the following example:

    <?php    class FileNotExistException extends Exception {}    class FileReadException extends Exception {}    class FileEmptyException extends Exception {}    $file = 'story.txt';    try {      try {        $content = file_get_contents($file);        if (!$content) {          throw new Exception();        }      }       catch (Exception $e) {        if (!file_exists($file)) {          throw new FileNotExistException();        }         elseif (!is_readable($file)) {          throw new FileReadException();        }  elseif (empty($content)) ...

Get Mastering PHP 7 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.