xxxxxxxxxx
# this raises a "NameError"
>>> raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere
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
#Best practive: raise statement
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
# 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!")