Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP handle null handling by exception

Is there a way I can tell PHP to throw an exception when I am trying to access a member or method on a null object?

E.g.:

$x = null;
$x->foo = 5; // Null field access
$x->bar(); // Null method call

Right now, I only get the following errors which are not nice to handle:

PHP Notice:  Trying to get property of non-object in ...
PHP Warning:  Creating default object from empty value in ...
PHP Fatal error:  Call to undefined method stdClass::bar() in ...

I would like to have a specific exception being thrown instead. Is this possible?

like image 621
gexicide Avatar asked Oct 05 '14 16:10

gexicide


People also ask

Does PHP have try catch?

The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.

Does throwing an exception stop execution PHP?

When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block. If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.

How can I get fatal error in PHP?

You can "catch" these "fatal" errors by using set_error_handler() and checking for E_RECOVERABLE_ERROR. I find it useful to throw an Exception when this error is caught, then you can use try/catch.


2 Answers

Since PHP7 you can catch fatal errors, example below:

$x = null;
try {
    $x->method();
} catch (\Throwable $e) {
    throw new \Exception('$x is null');
}
like image 155
HenryQ Avatar answered Sep 19 '22 18:09

HenryQ


You can turn your warnings into exceptions using set_error_handler() so when ever an warning occurs, it will generate an Exception which you can catch in a try-catch block.

Fatal errors can't be turned into Exceptions, they are designed for php to stop asap. however we can handle the fetal error gracefully by doing some last minute processing using register_shutdown_function()

<?php

//Gracefully handle fatal errors
register_shutdown_function(function(){
    $error = error_get_last();
    if( $error !== NULL) {
        echo 'Fatel Error';
    }
});

//Turn errors into exceptions
set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});

try{
    $x = null;
    $x->foo = 5; // Null field access
    $x->bar(); // Null method call
}catch(Exception $ex){
    echo "Caught exception";
}
like image 30
Krimson Avatar answered Sep 18 '22 18:09

Krimson