raise Exception or raise Exception() - python

I need to raise an exception. In my specific case NotImplementedError.
What is the difference between
Raise NotImplementedError and raise NotImplementedError().
Which is considered a better practice? Why?

There is no difference between raise X and raise X(). It's better to use the second form and pass a message like raise RuntimeError('bad argument'). If there is no useful message like your case I go with first syntax. It's a matter of taste.
The first form is a remaining of old style raising (not valid in Python3):
raise X, 'a'
is the same as
raise X('a')

Related

How to test for a bad expression in python for infix

def main1(expr):
if expr(eval) raise ValueError:
raise ValueError("Not a correct expression")
main1((8+3)*(5-6)))
So, I have the parameters this: (8+3)*(5-6))
However, I purposely put another parenthesis on this, making this infix expression invalid.
Is there a way to do this in my code, where it tries to evaluate it, and if it runs a error, raise a Value error stating that it is not a valid input?
What you are looking for is a try - catch.
Though to be honest there is no good reason to use this. The error that is raised is already a syntax error, which is the error that the user would expect if the syntax is wrong.
A better way of doing this may be:
def main1(expr):
try:
eval(expr)
except SyntaxError:
#logger.error("This is not a correct expression")
print("This is not a correct expression")
raise
Or if you are set on this decision, this should do what you want.
def main1(expr):
try:
eval(expr)
except SyntaxError:
raise ValueError("Not a correct expression")
main1("(8+3)*(5-6))")

Raising a "null" exception in Python

I am trying to write a function that does error checking in the following way.
def check_var_type(var, var_name, type):
t = type(var)
if t is type or t is list:
return None
else:
return TypeError(
f"Invalid {var_name} type '{t.__module__}.{t.__name__}', "
f"'{float.__module__}.{float.__name__}' or "
f"'{list.__module__}.{list.__name__}' expected.")
my_var = 1
raise check(my_var, 'my_var', float)
My expectation of Python's raise command was that if I pass None to it, it would simply ignore it and raise no exception. The response, however, was:
TypeError: exceptions must derive from BaseException
I then had a look at Python's built-in exception types to see if something like Nonthing, NoError, etc. exists. No luck though.
I can, of course raise the exception in the check_var_type function, but I don't want to, since this would add an extra line to the stack trace.
So, my (perhaps silly) question is: How can I use raise to not raise an exception? :-)
Thanks
If you don't want to raise an exception, don't call raise (whose sole job IS to raise an exception).
Perhaps what you really want is to call raise from inside check_var_type when you actually do want to raise an exception, and just use return when you don't.
An alternative might be to leave check_var_type as is, but wrap the call to it in an if that one raises the exception returned when an exception is returned.

In Python is there any reason to use try/except if errors are just going to be re-raised?

Is there any best practice, stylistic or programmatic reason to catch StandardErrors if I'm just going to re-raise them?
In other words, is it better for any reason to do this:
try:
do_something()
except StandardError:
raise
Instead of just this:
do_something()
I see this question Does a exception with just a raise have any use? which says that this is often used when some errors are pass and others are raise which I understand; and it suggests that the former is more useful for documentation (?) and as placeholders for future, which are both human-level reasons.
I'm just wondering if there's any lower-level answer, or even just which would be considered more Pythonic?
If you want to log your errors (for example) you can do this:
try:
do_something()
except StandardError as ex:
print(ex)
raise
And just
try:
do_something()
except StandardError:
raise
explicitly shows that you know about possible exception but don't want to catch it.

How to use "raise" keyword in Python [duplicate]

This question already has answers here:
Manually raising (throwing) an exception in Python
(11 answers)
Closed 4 years ago.
I have read the official definition of "raise", but I still don't quite understand what it does.
In simplest terms, what is "raise"?
Example usage would help.
It has two purposes.
jackcogdill has given the first one:
It's used for raising your own errors.
if something:
raise Exception('My error!')
The second is to reraise the current exception in an exception handler, so that it can be handled further up the call stack.
try:
generate_exception()
except SomeException as e:
if not can_handle(e):
raise
handle_exception(e)
raise without any arguments is a special use of python syntax. It means get the exception and re-raise it. If this usage it could have been called reraise.
raise
From The Python Language Reference:
If no expressions are present, raise re-raises the last exception that
was active in the current scope.
If raise is used alone without any argument is strictly used for reraise-ing. If done in the situation that is not at a reraise of another exception, the following error is shown:
RuntimeError: No active exception to reraise
It's used for raising errors.
if something:
raise Exception('My error!')
Some examples here
Besides raise Exception("message") and raise Python 3 introduced a new form, raise Exception("message") from e. It's called exception chaining, it allows you to preserve the original exception (the root cause) with its traceback.
It's very similar to inner exceptions from C#.
More info:
https://www.python.org/dev/peps/pep-3134/
You can use it to raise errors as part of error-checking:
if (a < b):
raise ValueError()
Or handle some errors, and then pass them on as part of error-handling:
try:
f = open('file.txt', 'r')
except IOError:
# do some processing here
# and then pass the error on
raise
raise causes an exception to be raised. Some other languages use the verb 'throw' instead.
It's intended to signal an error situation; it flags that the situation is exceptional to the normal flow.
Raised exceptions can be caught again by code 'upstream' (a surrounding block, or a function earlier on the stack) to handle it, using a try, except combination.

When is "raise Class, instance" useful?

If you have an exception instance, why would you need to specify its class?
What's the advantage over simply raise instance?
There is no advantage. raise Class, instance is a legacy expression and is completely equivalent to raise instance. Especially, the first notation is removed in Python 3 and replaced by the latter.
There's no reason ever to use it really. It's archaic usage from back before exceptions had to be class instances, and it's gone in Python 3.
You can pass one exception for another:
exc = StopIteration('Iterator has already exhaused!')
try:
raise ValueError, exc
except ValueError, e:
print e.args[0]
Good practical uses of this still elude me, though there must be some.

Categories

Resources