Exceptions Are Bad Yet Awesome!
Published: 2020-01-28 09:40:48

---
title: Exceptions Are Bad Yet Awesome!
published: true
tags: 
canonical_url: https://codeinphp.github.io/post/exceptions-are-bad-yet-awesome/
---

## Overview

At first thought, the words **errors** and **exceptions** give the general idea that they are the same thing or collectively _errors_ especially to the beginners. For example, when we see this:

`Fatal error: Call to undefined method Foo::bar()`

Or this:

`Exception: Method is not callable by this object`

Most beginner developer would concluded that those are just errors that need to be fixed and that may be right in a superficial sense because both of those messages are bad and need to be fixed anyway but in reality they are different things. The first one is an **Error** while later one is an **Exception**. Once we understand there can be _both errors and exceptions_ and how to successfully handle each, we can surely write better code.

In this post, we will see how we can deal with both of them and even create our own custom error and exception handlers for more control over how we want them to be displayed or handled while following best practices.

# Difference between Errors and Exceptions

**Errors**

- 

Errors are errors that are emitted by the programming language and you need to fix them.

- 

There can be syntax errors or logic errors. In PHP, there are different _levels_ of errors such as `ERROR`, `PARSE`, `WARNING`, `NOTICE`, `STRICT`. Some errors levels halt the further execution of your PHP script (such as `FATAL` errors) while others allow it to continue while presenting useful information that might also need to be fixed or payed attention to such as `WARNING` or `NOTICE`. And finally there are other error levels that can tell whether a particular function is deprecated (`DEPRECATED`) or whether or not standards are being followed (`STRICT`).

- 

Errors can be converted into user-thrown exceptions while still some being recoverable other not because they are emitted by core programming language

- 

We can emit custom/user errors through [`trigger_error()`](http://php.net/manual/en/function.trigger-error.php) function

- 

We can create custom error handler for all errors using [`set_error_handler()`](http://php.net/manual/en/function.set-error-handler.php)

- The [`error_get_last`](http://php.net/manual/en/function.error-get-last.php) function can be used to get any error that happened last in PHP code. The [`$php_errormsg`](http://php.net/manual/en/reserved.variables.phperrormsg.php) variable can be used to get previous error message.

**Exceptions** :

- 

Exceptions are object oriented approach to errors and are thrown intentionally by code/developer and should be handled/caught using `try - catch -finally` blocks

- 

An `Exception`is a standard class that can be used like any other class and can also be extended.

- 

Exceptions can have many types (through sub-classes) while errors can only have levels mentioned above.

- 

Exceptions can be caught at any point in the call stack and can also be caught at root/default exception handler. In comparison, errors are only handled in pre-defined error handler.

- 

We can throw custom/user exceptions by using `throw new Exception(...)`

- We can create custom exception handler for all exceptions using [`set_exception_handler()`](http://php.net/manual/en/function.set-exception-handler.php)

## General Practice

Nowadays, it seems common (and better) practice to always throw exceptions (even for errors) from your code so that they can be caught and dealt with in caller script. Of course if we throw an exception for error which is `FATAL`, we can't recover from it but we can still provide OOP approach to caller script. If you have used `MySQL` extension, you would notice that it emits normal errors if something goes wrong; here is an example when connection to database could not be made:

`Warning: mysql_connect(): Access denied for user 'root'@'localhost'`

Notice that it emits error level of `Warning`. This is just an example for the function `mysql_connect` but other functions of `MySQL` extension also emit errors in the same way and can be grabbed with [`mysql_error()`](http://php.net/manual/en/function.mysql-error.php) function.

But if you use improved version of MySQL called `MySQLi` or even `PDO`, you would notice they can now also throw exceptions, here is same example if connection could not be made to database using `mysqli`:

```
mysqli_report(MYSQLI_REPORT_STRICT); // tell mysqli to generate exceptions as well
mysqli_connect('localhost', 'root', 'wrongPassword', 'test');
```

It would give you both error as well as exception:

`Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Access denied for user 'root'@'localhost'`

`mysqli_sql_exception: Access denied for user 'root'@'localhost' (using password: YES)`

So these days any good written package or library or some extension you use, it would most likely generate Exceptions of its own type so that they can be caught and handled gracefully.

## How Do Exceptions Help ?

Let's understand through example. Let's say you want to connect to database using `mysql` and you would normally do something like this:

```
mysql_connect('localhost', 'root', 'wrongPassword', 'test');
```

If connection could not be made to database, you would receive error:

`Warning: mysql_connect(): Access denied for user 'root'@'localhost'`

Now the **_only_** thing you can do is go to your code and edit it to specify correct database credentials.

Let's now do the same thing using `mysqli`:

```
mysqli_report(MYSQLI_REPORT_STRICT); // tell mysqli to generate exceptions as well
mysqli_connect('localhost', 'root', 'wrongPassword', 'test');
```

This would generate an error as well as exception as shown previously. Since exception is generated, we can catch it and show the message:

```
try {    
    mysqli_connect('localhost', 'root', 'wrongPassword', 'test');
} catch (mysqli_sql_exception $e) {
    echo $e->getMessage();
}
```

The reason why exception is useful here is because you are given a chance to catch that exception gracefully. Inside `catch` block, we can handle the exception however we want. For the sake of example, let's say we want to connect to database again with correct password this time:

```
mysqli_report(MYSQLI_REPORT_STRICT);

try {    
    mysqli_connect('localhost', 'root', 'wrongPassword', 'test');
} catch (mysqli_sql_exception $e) {
    mysqli_connect('localhost', 'root', 'rightPassword', 'test');
}
```

And thanks to exception, we were able to catch it and handle it the way we needed and we are now connected to database which was simply not possible with previous example using `mysql` which only emitted an error and we couldn't do much. Of course in real world applications, you might not have different passwords to connect to database but this example just gives an idea of _how_ exceptions can be useful.

As another example, let's say we want read feed/rss of some website using [SimpleXML](http://php.net/manual/en/book.simplexml.php) (which can also throw exceptions) and store 10 posts in an array:

```
$feedUrl = 'http://some_feed_url';
$feeds = file_get_contents($feedUrl);
$xml = new SimpleXmlElement($feeds);

$articles = array();
foreach ($xml->channel->item as $item) {
   $item = (array) $item;
   $articles[] = array('title' => $item['title'], 'link' => $item['link']);
}

$data['articles'] = array_slice($articles, 0, 10);
```

This would work as long as feed url is correct and has posts but if url is wrong, you would see a `Fatal` error as well `Exception` being generated by the script:

`Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML`

`Exception: String could not be parsed as XML`

Since it is `FATAL` error, our script died at that point and we can't do anything. How do we ensure that our script continues working and runs any code below that feed code even if provided feed url was wrong ? Of course we need to `catch` the exception since as we saw it also generated an `Exception`:

```
try {
    $feedUrl = 'http://some_feed_url';
    $feeds = file_get_contents($feedUrl);
    $xml = new SimpleXmlElement($feeds);

    $articles = array();
    foreach ($xml->channel->item as $item) {
       $item = (array) $item;
       $articles[] = array('title' => $item['title'], 'link' => $item['link']);
    }

    $data['articles'] = array_slice($articles, 0, 10);
} catch (Exception $e) {

}

echo 'Hello World';
```

And now since we have wrapped our code in `try-catch` and caught the exception, our code below that should still run. In this case even if feed url was wrong, you should still see the `Hello World` message. Our script didn't die and continued its execution. So those two examples should now give idea of how useful exceptions can be when used.

## How do I convert Errors into Exceptions?

To do so ,we can use the [`set_error_handler()`](http://php.net/manual/en/function.set-error-handler.php) function and throw exceptions of type [`ErrorException`](http://php.net/manual/en/class.errorexception.php) something like:

```
set_error_handler(function ($errorNumber, $errorText, $errorFile, $errorLine ) 
{
    throw new ErrorException($errorText, 0, $errorNumber, $errorFile, $errorLine);
});
```

With that custom exception now in place, you can do things like:

```
try {
    // wrong url
    file_get_contents('http://wrong_url');
} catch (ErrorException $e) {
    // fix the url
    file_get_contents('http://right_url');
}
```

So in `catch` block, we are now able to fix the URL for the `file_get_contents` function. Without this exception, we could do nothing but may be suppressing the error by using [error control operator @](http://php.net/manual/en/language.operators.errorcontrol.php).

## Universal Exception Handler

Now that we have seen how useful exceptions are and how to convert errors into exceptions, we can create our custom universal exception handler that can be used throughout the application. It will always generate exceptions not errors. It will do these things:

1 - Allow us to tell it our environment which can be either `development` or `production`

2 - In case of `production` environment, it will log all errors to a file instead of displaying them on screen

3 - In case of `development` environment, it will display all errors on the screen

```
/**
 * A class that handles both errors and exceptions and generates an Exception for both.
 *
 * In case of "production" environment, errors are logged to file
 * In case of "development" environment, errors are echoed out on screen
 *
 * Usage:
 *
 * new ExceptionHandler('development', '/myDir/logs');
 *
 * Note: Make sure to use it on very beginning of your project or bootstrap file.
 *
 */
class ExceptionHandler {
    // file path where all exceptions will be written to
    protected $log_file = '';
    // environment type
    protected $environment = '';

    public function __construct($environment = 'production', $log_file = 'logs')
    {
        $this->environment = $environment;
        $this->log_file = $log_file;

        // NOTE: it is better to set ini_set settings via php.ini file instead to deal with parse errors.
        if ($this->environment === 'production') {
            // disable error reporting
            error_reporting(0);
            ini_set('display_errors', false);
            // enable logging to file
            ini_set("log_errors", true);
            ini_set("error_log", $this->log_file);
        }
        else {
            // enable error reporting
            error_reporting(E_ALL);
            ini_set('display_errors', 1);
            // disable logging to file
            ini_set("log_errors", false);
        }

        // setup error and exception handlers
        set_error_handler(array($this, 'errorHandler'));
        set_exception_handler(array($this, 'exceptionHandler'));        
    }

    public function exceptionHandler($exception)
    {
        if ($this->environment === 'production') {
            error_log($exception, 3, $this->log_file);
        }

        throw new Exception('', null, $exception);
    }

    public function errorHandler($error_level, $error_message, $error_file, $error_line)
    {
        if ($this->environment === 'production') {      
            error_log($message, 3, $this->log_file);
        }

        // throw exception for all error types but NOTICE and STRICT
        if ($error_level !== E_NOTICE && $error_level !== E_STRICT) {
            throw new ErrorException($error_message, 0, $error_level, $error_file, $error_line);
        }        
    }
}
```

Test it:

```
// register our error and exceptoin handlers
new ExceptionHandler('development', 'logs');

// create error and exception for testing
trigger_error('Iam an error but will be converted into ErrorException!');
throw new Exception('I am an Exception anyway!');
```

So that is an example of _basic_ universal error and exception handler class. Actually you can do a lot more like customizing the display of messages, getting the stack trace as well as code that caused it, creating timestamp for when those events take place, etc. You should checkout the official documentation in order to achieve those goodies. At any point in your code, you want to restore original PHP's error and exception handlers, you can use [`restore_error_handler()`](http://php.net/manual/en/function.restore-error-handler.php) and [`restore_exception_handler()`](http://php.net/manual/en/function.restore-exception-handler.php) functions.

## Conclusion

No exception to exceptions!

* * *

As a side note, I personally hope someday a PSR standard is created for handling errors and exceptions and their best practices because they are integral part of any PHP code.

 ![](http://feeds.feedburner.com/~r/codeinphpfeed/~4/f5VSKevMhF4)