Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between raising Exception class and Exception instance?

Tags:

In Python, I can raise an Exception in two ways

raise ValueError
raise ValueError()

apart from the fact that you can supply exception message in latter case, is there any fundamental difference between these two styles? Should I choose one over the other?

like image 415
yasar Avatar asked Nov 04 '13 13:11

yasar


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.

What does raising exception mean?

Raising an exception is a technique for interrupting the normal flow of execution in a program, signaling that some exceptional circumstance has arisen, and returning directly to an enclosing part of the program that was designated to react to that circumstance.

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.

What does raise exception return?

Raising an exception terminates the flow of your program, allowing the exception to bubble up the call stack. In the above example, this would let you explicitly handle TypeError later. If TypeError goes unhandled, code execution stops and you'll get an unhandled exception message.


1 Answers

from the doc both are valid (no unexpected behaviour):

The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception).

In my opinion, an instance need to be used if you want it to hold data, whether it is a message (as you said) or custom data or whatever.

as @alko said, if you don't give an instance it will instantiate one with no argument.

this won't work if you need a mandatory argument:

>>> class MyError(Exception):
...    def __init__(self, message, data=None):
...       self.msg = message
...       self.data = data or {}
...
>>> raise MyError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() takes at least 2 arguments (1 given)
like image 145
astreal Avatar answered Oct 20 '22 02:10

astreal