Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I instantiate an exception without throwing it?

Tags:

php

php-5.4

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...
like image 680
Alex Avatar asked Jul 11 '13 09:07

Alex


People also ask

Can we throw an exception without throws?

Without using throwsWhen an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception objects). If you re-throw the exception, just like in the case of throws clause this exception now, will be generated at in the method that calls the current one.

Can exceptions be instantiated?

The InstantiationException is a runtime exception in Java that occurs when an application attempts to create an instance of a class using the Class. newInstance() method, but the specified class object cannot be instantiated.

Does throwing an exception stop execution Java?

When an exception is thrown the method stops execution right after the "throw" statement. Any statements following the "throw" statement are not executed.

How do you force an exception?

Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.


1 Answers

Yes, an exception is just like any other object.

like image 143
Tom van der Woerdt Avatar answered Oct 09 '22 01:10

Tom van der Woerdt