Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between "raise exception()" and "raise exception" without parenthesis?

Defining a parameterless exception:

class MyException(Exception):     pass 

When raised, is there any difference between:

raise MyException 

and

raise MyException() 

I couldn't find any; is it simply an overloaded syntax?

like image 222
Ohad Dan Avatar asked May 23 '13 06:05

Ohad Dan


People also ask

What is the difference between raising an exception and handling an exception?

except is how you handle an exception that some other code signalled. raise is how you signal an exception yourself. It's like asking what the difference is between making a phone call and answering the phone. In except you usually handle exceptions, you normally don't raise other exceptions.

How do I manually raise exceptions?

Throwing exceptions manually To throw an exception explicitly you need to instantiate the class of it and throw its object using the throw keyword.

Can we use raise without exception in Python?

Only an exception handler (or a function that a handler calls, directly or indirectly) can use raise without any expressions.

What is the difference between raising an exception and handling an exception Python?

raise allows you to throw an exception at any time. assert enables you to verify if a certain condition is met and throw an exception if it isn't. In the try clause, all statements are executed until an exception is encountered. except is used to catch and handle the exception(s) that are encountered in the try clause.


1 Answers

The short answer is that both raise MyException and raise MyException() do the same thing. This first form auto instantiates your exception.

The relevant section from the docs says:

raise evaluates the first expression as the exception object. It must be either a subclass or an instance of BaseException. If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments.

That said, even though the semantics are the same, the first form is microscopically faster, and the second form is more flexible (because you can pass it arguments if needed).

The usual style that most people use in Python (i.e. in the standard library, in popular applications, and in many books) is to use raise MyException when there are no arguments. People only instantiate the exception directly when there some arguments need to be passed. For example: raise KeyError(badkey).

like image 143
Raymond Hettinger Avatar answered Sep 23 '22 10:09

Raymond Hettinger