Exception

By ukmodak | March 31st 2024 10:36:23 AM | viewed 221 times

List of available built-in exception classes since PHP 7.4:

  1. Exception
  2. ErrorException
  3. Error
  4. ArgumentCountError
  5. ArithmeticError
  6. AssertionError
  7. DivisionByZeroError
  8. CompileError
  9. ParseError
  10. TypeError

Error, what?

In previous versions of PHP, errors were treated quite differently than exceptions. An error was something that was produced in the engine and as long as it was not fatal, it could be handled by a user-defined function.

The problem was that there were several errors that were fatal and that could not be handled by a user-defined error handler. This meant that you couldn’t handle fatal errors in PHP gracefully. There were several side-effects that were problematic, such as the loss of runtime context, destructors would not be called and dealing with them was clunky. In PHP 7, fatal errors are now exceptions and we can handle them very easily. Fatal errors result in an error exception being thrown. You need to handle non-fatal errors with an error-handling function.

Here is an example of catching a fatal error in PHP 7.1. Notice how the non-fatal error is not caught.

try {
   // this will generate notice that would not be caught
   echo $someNotSetVariable;
   // fatal error that now actually is caught
   someNoneExistentFunction();
} catch (Error $e) {
      echo "Error caught: " . $e->getMessage();
}

op:
Notice: Undefined variable: someNotSetVariable on line 3
Error caught: Call to undefined function someNoneExistentFunction()

This script will output a notice error for the attempt to access an invalid variable. Trying to call a function that does not exist would result in a fatal error in earlier versions of PHP, but in PHP 7.1 you can catch it. Here is the output for the script:

Error constants

PHP has a lot of constants that are used in relation to errors. These constants are used when configuring PHP to hide or display errors of certain classes.

  • E_DEPRECATED – the interpreter will generate this type of warnings if you use a deprecated language feature. The script will definitely continue to run without errors.
  • E_STRICT – similar to E_DEPRECATED, this indicates that you are using a language feature that is not standard currently and might not work in the future. The script will continue to run without any errors thrown.
  • E_PARSE – your syntax could not be parsed so your script won’t start. Script execution will not even start.
  • E_NOTICE – the engine will just print out an informational message. Script execution won’t break and none of the errors will be thrown.
  • E_ERROR – the script cannot continue running and it is being terminated. Will throw errors and how these are going to be handled depends on the error handler.
  • E_RECOVERABLE_ERROR – it indicates that a probably dangerous error occurred, but did not leave the Engine in an unstable state. Further execution depends on the error handler and error will definitely be thrown.
  • E_ALL- All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)

Error handler function

The set_error_handler() function is used to tell PHP how to handle standard engine errors that are not instances of the Error exception class. You cannot use an error-handler function for fatal errors. Error exceptions must be handled with try/catch statements. set_error_handler() accepts a callable as its parameter. Callables in PHP can be specified in two ways: either by a string denoting the name of a function or by passing an array that contains an object and the name of a method (in that order). You can specify protected and private methods as the callable in an object. You can also pass null to tell PHP to revert to the usage of the standard error-handling mechanism. If your error handler does not terminate the program and returns, your script will continue executing at the line after the one where the error occurred.

You can write your own function to handling any error. PHP provides you a framework to define error handling function. This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context) −

error_function(error_level,error_message, error_file,error_line,error_context);
error_reporting( E_ALL );
   
   function handleError($errno, $errstr,$error_file,$error_line) {
      echo "Error: [$errno] $errstr - $error_file:$error_line";
      echo "
"; echo "Terminating PHP Script"; die(); } //set error handler set_error_handler("handleError"); //trigger error myFunction();
function myCustomErrorHandler(int $errNo, string $errMsg, string $file, int $line) {
echo "Wow my custom error handler got #[$errNo] occurred in [$file] at line [$line]: [$errMsg]";
}

set_error_handler('myCustomErrorHandler');

try {
   what;
} catch (Throwable $e) {
   echo 'And my error is: ' . $e->getMessage();
}

op:
Error #[2] occurred in [php shell code] at line [3]: [Use of undefined constant what - assumed 'what' (this will throw an Error in a future version of PHP)]

Displaying or suppressing the non-fatal error message

When you application reaches production, you want to hide all system error messages while in production and your code must run without generating warnings or messages. If you are going to show an error message, make sure that it is the one you’ve generated and that it does not include information that could help an attacker break into your system.

In your development environment, you want all errors to be displayed so that you can fix all the issues they relate to, but while in production, you want to suppress any system messages being sent to the user.

To accomplish this, you need to configure PHP using the following settings in your php.ini file:

  • display_errors – can be set to false to suppress messages
  • log_errors – can be used to store error messages in log files
  • error_reporting – can be set to configure which errors trigger a report

The best practice is to handle errors in your application gracefully. In production, you should rather log unhandled errors instead of allowing them to be displayed to the user. The error_log() function can be used to send a message to one of the defined error handling routines. You can also use the error_log() function to send emails, but personally, would rather use a good solution for logging errors and receiving notifications when an error occurs like Sentry or Rollbar.

There is a thing called Error Control Operator – the at-sign (@) – that in the essence can ignore and suppress errors. The usage is very easy – just prepend any PHP expression with at-sign and generated error will be ignored. Although using this operator may look interesting, I urge you not to do that. I like to call it the living relict from the past.

Exceptions

Exceptions are a core part of object-oriented programming and were first introduced in PHP 5.0. An exception is a program state that requires special processing because it’s not running in an expected manner. You can use an exception to change the flow of your program, for example, to stop doing something if certain preconditions are not met.

class MyCustomException extends Exception { }

function throwMyCustomException() {
      throw new MyCustomException('There is something wrong.');
}

try {
   throwMyCustomException();
} catch (MyCustomException $e) {
   echo "Your custom exception caught ";
   echo $e->getMessage();
} catch (Exception $e) {
   echo "PHP base exception caught";
}

class MyCustomException extends Exception { }
class MyAnotherCustomException extends Exception { }

try {
   throw new MyAnotherCustomException;
} catch (MyCustomException | MyAnotherCustomException $e) {
   echo "Caught : " . get_class($e);
}
class MyCustomException extends Exception { }

function throwMyCustomException() {
   throw new MyCustomException('There is something wrong.');
}

try {
   throwMyCustomException();
} catch (MyCustomException $e) {
   echo "Your custom exception caught ";
   echo $e->getMessage();
} catch (Exception $e) {
   echo "PHP base exception caught";
} finally {
  echo "I'm always here";
}

There are following functions which can be used from Exception class.

  • getMessage() − message of exception
  • getCode() − code of exception
  • getFile() − source filename
  • getLine() − source line
  • getTrace() − n array of the backtrace()
  • getTraceAsString() − formated string of trace

Exception handler function

Any exception that is not caught results in a fatal error. If you want to respond gracefully to exceptions that are not caught in catch blocks, you’ll need to set a function as the default exception handler.

To do so, you use the set_exception_handler() function, which accepts a callable as its parameter. Your script will terminate after the callable has executed.

The function restore_exception_handler() will revert the exception handler to its previous value.

class MyCustomException extends Exception { }

function exception_handler($exception) {
   echo "Uncaught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

try {
   throw new Exception('Uncaught Exception');
} catch (MyCustomException $e) {
   echo "Your custom exception caught ";
   echo $e->getMessage();
} finally {
   echo "I'm always here";
}

print "Not executed";
function exception_handler($exception) {
      echo "Uncaught exception: " , $exception->getMessage(), "\n";
   }
	
   set_exception_handler('exception_handler');
   throw new Exception('Uncaught Exception');
   
   echo "Not Executed\n";
bONEandALL
Visitor

Total : 20973

Today :27

Today Visit Country :

  • Germany
  • United States
  • Singapore
  • China
  • United Kingdom
  • South Korea
  • Czechia