Can I instantiate an exception without throwing it?
Asked Answered
R

2

6

I am using a SaaS error and exception logging service called Rollbar. In my code, I have a Rollbar static object that I can use to report exceptions to the service.

For example:

try {
    ...
    throw new SomeException();
    ...
} catch (SomeException $e) {
    Rollbar::report_exception($e);
}

My question is: Can I instantiate an exception without throwing it, as if it were any other normal object, and are there any caveats?

I would like to do things like this:

if($api_response_ok) {
    // Do some stuff
    ...
} else {
    Rollbar::report_exception(new ApiException($api_error_msg));
}

// Script execution continues...
Rothmuller answered 11/7, 2013 at 9:45 Comment(4)
What's the reason for the downvote? I can improve the question.Rothmuller
I was wondering the same - my answer also got downvoted. Here, have this upvoteFissile
I'm not sure as I didn't downvote, but it could be because you could have easily answered this for yourself just by trying.Eczema
Technically yes, but a test like that would have only answered my question under the conditions of that test (test code, PHP version, etc). I don't really like to assume a given behaviour is the intended outcome based on my own experiments, when the behaviour isn't made clear in the documentation. As such, seeking more reliable advice or an authoritative answer from others with more knowledge and experience than me seems acceptable enough.Rothmuller
F
8

Yes, an exception is just like any other object.

Fissile answered 11/7, 2013 at 9:47 Comment(0)
P
1

Exceptions are only objects that extend the Exception class. They will only break the script execution when they are thrown.

$exception = new Exception('Die');
//Does not exit here
throw $exception;
//Will exit here
Polypoid answered 11/7, 2013 at 9:48 Comment(2)
Mine wasn't the downvote, but my guess is it's probably because throwing an exception doesn't "exit" the script, or "break the script execution", per se - rather, it causes PHP to stop executing the code in the current scope and search up the stack frame for an appropriate catch block.Rothmuller
@Alex, thats a bit hypercritical. I think George is referring to the current script context rather than the whole program.Ribal

© 2022 - 2024 — McMap. All rights reserved.