xxxxxxxxxx
# Raise a built-in exception
raise ValueError("Invalid value entered!")
# Raise a custom exception
class MyCustomException(Exception):
pass
raise MyCustomException("This is a custom exception!")
xxxxxxxxxx
# You can raise a error in python by using the raise keyword
raise Exception("A error occured!")
xxxxxxxxxx
def prefill(n,v):
try:
n = int(n)
except ValueError:
raise TypeError("{0} is invalid".format(n))
else:
return [v] * n
xxxxxxxxxx
#raise exception
raise ValueError('A very specific bad thing happened.')
xxxxxxxxxx
raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
xxxxxxxxxx
# Basic syntax:
raise Exception("An error occured")
# Example usage:
# Say you want to raise an error when a file isn't found, you could do:
raise FileNotFoundError("Error, the file you requested wasn't found")
# Note, for a complete list of built-in exceptions, see this documentation:
# https://docs.python.org/3/library/exceptions.html#bltin-exceptions
xxxxxxxxxx
# Raise a specific exception
raise ValueError("This is a custom error message")
# Raise a generic exception
raise Exception("This is a generic error message")
xxxxxxxxxx
# The proper procedure is to raise the new exception inside of the __exit__ handler.
# You should not raise the exception that was passed in though; to allow for context manager chaining, in that case you should just return a falsey value from the handler. Raising your own exceptions is however perfectly fine.
# Note that it is better to use the identity test is to verify the type of the passed-in exception:
def __exit__(self, ex_type, ex_val, tb):
if ex_type is VagueThirdPartyError:
if ex_val.args[0] == 'foobar':
raise SpecificException('Foobarred!')
# Not raising a new exception, but surpressing the current one:
if ex_val.args[0] == 'eggs-and-ham':
# ignore this exception
return True
if ex_val.args[0] == 'baz':
# re-raise this exception
return False
# No else required, the function exits and `None` is returned
# You could also use issubclass(ex_type, VagueThirdPartyError) to allow for subclasses of the specific exception.
xxxxxxxxxx
# this raises a "NameError"
>>> raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere