Rahul Bhatnagar
Rahul Bhatnagar

Reputation: 106

PHP Try Catch Finally Issue

I got stuck working in an error logging piece that I'm working on, and ultimately it devolved into the following:

$errorMsg = 'No Errors Detected';
try{
    nonexistentfunction();     //Basically something here will not work
}catch(Exception $e){
    $errorMsg = 'Oh well, something went wrong';
}finally{
    $this->logger->log($errorMsg);
}

However, every time the logger logs the message 'No Errors Detected' while it should be logging 'Oh well, something went wrong' because I'm throwing an exception (method not found in this example, but any exception can occur).

How do I get the code in the catch() block to execute? It doesn't seem to execute at all!

Upvotes: 0

Views: 1031

Answers (1)

fubar
fubar

Reputation: 17388

If you call an undefined function in PHP, it'll throw a fatal error, not an exception.

You'd therefore need to catch an object of type Error. Alternatively, you can catch Throwable objects, from with both Error and Exception classes extend.

http://php.net/manual/en/language.errors.php7.php

<?php

$errorMsg = 'No Errors Detected';

try {
    nonexistentfunction();
}
catch (Throwable $e) {
    $errorMsg = 'Oh well, something went wrong';
}
finally{
    $this->logger->log($errorMsg);
}

Upvotes: 4

Related Questions