What Are Laravel Exceptions?

As a PHP developer, you may use exceptions, because they allow you to notice when something has gone wrong or the user has acted in an unusual way (such as division by zero). Without exceptions, your application would end up presenting unwanted errors and being much more difficult to debug. It is also important that you halt execution immediately and take another course of action.

Exceptions are really simple, and they will make your development progress easier. When you learn how to use exceptions, this will be a usual part of your development.

What Is an Exception?

Exceptions signal something outside the expected bounds of behavior of the code in question.

Exactly, in fact, an exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions. When you throw (create an exception object and hand it to the runtime system) an exception, the system will catch it by searching for the appropriate handler and returning the proper message.

When Do We Need to Use Exceptions?

Use exceptions when your system is faced with exceptional circumstances that prevent the system from taking over. We use exceptions only when the system is not able to determine what has happened. Martin Fowler believes that “if a failure is expected behavior, then you shouldn’t be using exceptions”. This means you should use exceptions where you are not able to determine the error. Exceptions should only be used in exceptional circumstances.

Note: Exceptions are not good for handling logic operations.

For a system like validating input, using exceptions is wrong. First of all, the input text will be determined, and in an application like this we should report a collection of errors instead of a single error. I believe in eliminating the use of exceptions in any circumstance where we might expect validation failures.

Catching an exception is very important, because if you do not catch an exception the system will return an error. The catching operation must be as close to the point of failure as possible.

What Are Laravel Exceptions?

Laravel uses exception Handler, which is a class in App\Exceptions\Handler.php. This class contains two main methods (the renderHttpException method, which is used for all HTTP Exceptions, like 404s and 503s, is in the parent class of Handler). The first one is report, which is used to log exceptions or send them to an external service. Here’s an example of the report method:

How to Create Your Own Laravel Exception?

You may need to create your own exception class. You need to extend from the Laravel base Exception class—I’ve created an abstract class that will behave as the base class of our custom Exception class. Create a file in App/Exceptions/monException.php: