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?
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With