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 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
# Example 1: Basic exception raising with custom message
try:
raise Exception("This is a custom error message")
except Exception as e:
print(e)
# Example 2: Creating a custom exception class with custom message
class CustomException(Exception):
def __init__(self, message):
self.message = message
try:
raise CustomException("This is a custom exception with a custom error message")
except CustomException as ce:
print(ce.message)
xxxxxxxxxx
# this raises a "NameError"
>>> raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere
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!")