Home » Php » php – Catch an exception without doing anything in the catch

php – Catch an exception without doing anything in the catch

Posted by: admin April 23, 2020 Leave a comment

Questions:

In PHP, I sometimes catch some exceptions with try/catch :

try {
    ...
} catch (Exception $e) {
    // Nothing, this is normal
}

With that kind of code, I end up with the variable $e that is created for nothing (lots of resources), and PHP_MD (PHP Mess Detector) creates a warning because of an unused variable.

Is there a way to catch an Exception without having to create a variable ?

Thanks

How to&Answers:

No, but you can unset it.

try {
    ...
} catch (Exception $e) {
    unset($e);
}

I’m assuming you are only catching the exception because you have to not because you want to.
You have to use a catch if you want to use try. so peoples opinions on whether its a bad idea to catch the exception is irrelevant.
Efforts should be put towards achieve the required result without using try/catch.
As far as I’m aware there is no alternative.

I use something like this for my templating engine.

//array of templates ordered by version new to old.
for($templates as $tpl){
    try {
        $output = render($tpl,$data);
        //it worked
        break;
    } catch(ErrorException $e){
        unset($e);
    }
}
if(!empty($output)){
    return $output;
}

Answer:

That’s the whole point of exceptions – you can have multiple different catch blocks to catch any exceptions you’d want to handle. The exception’s data has to be assigned somewhere, hence the variable. You could just do something like unset($e) inside the catch block if you really don’t want to see those warnings… or disable the warnings (generally a bad idea).

Answer:

No.

In any case, it’s generally a bad idea to catch an exception and do nothing; exceptions exist precisely to force you to handle the exceptional circumstance (otherwise execution is aborted), so it’s comprehensible the language doesn’t facilitate such a use case.

Answer:

I disagree fundamentally with Marc B’s and Artefacto’s answers. There are cases where ommitting the catch is better or even the only option. Especially when using external libraries (where you have no control over what exceptions are thrown) and/or async operations.

For example:

I want to create a file only if it doesn’t exist yet. I’m using an external I/O library. Imagine it has File::exists($fileName) and File::create($fileName) methods.

Option 1 (if ommitting the catch was possible):

try {
    File::create($fileName);
}
// Go on with the rest of the code.

Option 2 (without try/catch):

if (!File::exists($fileName))
    File::create($fileName);

Here, option 1 is perfectly valid, since option 2 has two important issues:

  1. If multiple threads are running and going through this code section at the same time, it could be that thread A first checks if the file exists. Next, thread B checks if the file exists. They both find that it doesn’t exist. Thread A creates the file. Thread B then attempts to create it again and throws an exception even though you’re using the if check.
  2. It’s very likely that the library itself already performs the !File::exists($fileName) check. Therefore you’re wasting a call that is already made.

Note that if File::create throws other exceptions that might be unexpected it would be good to catch those.

Conclusion

Stating that something is never a good idea, is almost never a good idea. There are always exceptions (hehe) to the rule. Like any convention or design pattern, it’s just a rule of thumb meant to help less experienced developers make the right decision.

Answer:

Exceptions are not only used for exceptional circumstances.

This scenario actually uses exceptions to make sure the user is logged out. At this point in the script it’s very resource expensive to figure out what data should be pruned so it’s actually faster to just prune it all and catch the exceptions.

        try {
        GDS::$DB->exec('DELETE FROM sessions WHERE session_id = ' . session_id());
        GDS::$DB->exec('DELETE FROM sessions WHERE user_id = ' . $this->data['user_id']);
    } catch(PDOException $ex) {}
    session_regenerate_id(true);
    setcookie('bis_[user_id]', 0, time() - 1, null, null, false, true);
    setcookie('bis_[session_start]', 0, time() - 1, null, null, false, true);
    setcookie('bis_[session_time]', 0, time() - 1, null, null, false, true);