EXCEPTIONS IN PHP

INTRODUCTION TO THE EXCEPTIONS

php logoSince PHP 5 we have the exception mechanism available. If we ask a user to enter a number between one and ten, the exception is when the number is outside this range. When we talk about exceptions we are talking about objects of class Exception. Let us take an example with the class FileManager. One exception arises with education

throw new Exception If we raise an exception someone somewhere will have to handle it, if not a fatal error occurs. Exceptions are caught with blocks try (try running the following code) catch (catch).

Class FileManager

The one shown next is the var_dump() which shows that the exception raised with new Exception is found inside the variable $e.

var_dump

PROPERTIES AND METHODS OF THE EXCEPTION CLASS

Property

RAISE AN EXCEPTION AND STACK TRACE

The code of the FileManager class is not good code considering we have many statements in the constructor and may need to insert more. The PHP interpreter after an exception has been raised looks in that code for a block try catch, if it does not find it it goes up the call stack until it finds one. If it doesn’t find it, the code ends with an unhandled exception. To demonstrate this, if we now bring the try catch inside the constructor we will see that we will not have any differences. Carry the code before the change.

Private method

When the exception is raised in the private method, PHP starts going up the stack; then, it passes into the constructor that invokes the method.

Stacktrace

At runtime, if not even a try catch block is found in the constructor, it will be searched for in the code that creates the object. If we move the try catch to that point we can still handle the error. Now the entire stack trace has been traversed backwards in search of a block that handles the error. If not found, an exception is thrown.

Stacktrace
CODICE GETTRACE

Let’s look at the var_dump of the getTrace() method.

get_trace

FINALLY BLOCK

The code contained within the block finally it always runs, whether we raise an exception or not. For example, it is used to close the connection to a database or file.

finally

EXTEND THE EXECPTION CLASS

Exception personalize

MANAGE MULTIPLE EXCEPTIONS

First the more specific catches are indicated, then being Exception the superclass this will catch all the exceptions not present in the catch blocks.

Exception multiple

HANDLING UNCATCHED EXCEPTIONS WITH SET_EXCEPTION_HANDLER

CATCHING MULTIPLE EXCEPTIONS IN THE CATCH BLOCK

By separating exceptions with the pipe symbol, you can catch multiple exceptions in the catch block.

Multiple catch exception

With set_exception_handler we can define a method to handle all uncaught exceptions.

Set_Exception_Handler

HANDLING EXCEPTIONS AND ERRORS WITH THROWABLE

We can talk about errors for something internally generated by PHP, exceptions for errors generated by the user and the use of the application itself. If we want, however, we could raise errors and not exceptions.

We cannot put Exception because the Error class is not a child class, it would result in a fatal error. Let’s go to the PHP documentation and look for the Error class.

Error
Class Error

Since the Error class implements the Throwable interface it means that we can use all the methods of the interface. Both the Exception class and the Error class implement this interface, this means that within the catch we can indicate Throwable. So whether we throw an exception or an error the application will work fine. There is, however, another evaluation to be made: It is true that with Throwable we catch a bit of everything however it is also true that by doing so we have no idea what was generated in the try, unless in the catch we write some code to know which object raised the exception using $e and instanceof.

List Exception

Using more specific exceptions the code is better at the semantic level, that is, whoever looks at the code could immediately understand that the problem generated in the try is a division by zero.

Throwable

FURTHER INFORMATION

Exceptions in PHP allow errors to be handled in a controlled manner, allowing the program to continue execution or terminate in an elegant manner.
When an error occurs in PHP, the engine generates an exception that can be “caught” and handled.
Exceptions are objects that are created from the base Exception class.

Basic syntax

Here is an example syntax for exception handling in PHP:

try {
      // Codice che potrebbe generare un’eccezione
      if ($condizione) {
           throw new Exception(“Messaggio d’errore”);
      }
} catch (Exception $e) {
      // Gestione dell’eccezione
      echoEccezione catturata: ” . $e->getMessage();
} finally {
      // Codice che viene sempre eseguito, sia in caso di eccezione che non
      echoQuesto blocco viene sempre eseguito.“;

Description of blocks

1. try: The try block contains code that could generate an exception.
If an exception occurs, the program flow goes to the catch block.

2. throw: The throw keyword is used to throw an exception manually.
It is used in conjunction with an instance of the Exception class (or a derived class thereof).

3. catch: The catch block is used to catch the exception and handle it.
It receives as argument the exception object, which can be used to get information such as the error message($e->getMessage()), the error code($e->getCode()) and other properties.

4. finally (optional): The finally block contains code that is executed whether an exception is thrown or not.
It is useful for operations to clean up or close resources such as files or database connections.

Main methods of the Exception class

-getMessage(): Returns the error message specified when throwing the exception.

-getCode(): Returns the error code, if provided.

-getFile(): Returns the name of the file where the exception was thrown.

-getLine(): Returns the line of code where the exception was thrown.

-getTrace(): Returns the stack trace array.

-getTraceAsString(): Returns the stack trace as a string.

Create custom exceptions

You can create your own custom exceptions by inheriting from the Exception class or one of its subclasses:

class MiaEccezione extends Exception {
       public function messaggioPersonalizzato() {
           returnErrore personalizzato: ” . $this->getMessage();
      }
}

try {
      throw new MiaEccezione(“Qualcosa è andato storto.“);
} catch (MiaEccezione $e) {
      echo $e->messaggioPersonalizzato();
}

Hierarchy of exceptions

In PHP, all exceptions are derived from the base Exception class.
There are also other ready-made exception classes, such as:

LogicException: Used for logic errors in the program.

RuntimeException: Used for errors that occur during program execution.

Complete example

class ErroreDiLogin extends Exception {
     // Classe di eccezione personalizzata
}

function login($utente, $password) {
         if ($utente !== “admin” || $password !== “1234“) {
             throw new ErroreDiLogin(“Credenziali non valide.“);
         }
         echoAccesso riuscito!“;
}

try {
         login(“utente“, “password“);
} catch (ErroreDiLogin $e) {
         echoEccezione catturata: ” . $e->getMessage();
} finally {
         echoChiusura connessione.“;
}

In this example, if the user and password are incorrect, a custom exception is thrown and the program catches the error.

LINKS TO PREVIOUS POSTS

THE PHP LANGUAGE

LINK TO THE CODE ON GITHUB

GITHUB