In Python, the raise
statement is used to explicitly raise an exception. This allows you to create custom exceptions and control the flow of your program when unexpected conditions occur.
Syntax
raise ExceptionType("Optional error message")
ExceptionType
is the type of exception you want to raise, and “Optional error message” is an optional string that provides more information about the error.
Examples
Raising a Built-in Exception
def divide(x, y): if y == 0: raise ZeroDivisionError("Cannot divide by zero!") return x / y try: result = divide(10, 0) except ZeroDivisionError as e: print(e)
In this example, the divide
function raises a ZeroDivisionError
if the divisor is zero. The try
block attempts to call the function, and the except
block catches the raised exception.
Raising a Custom Exception
class InvalidInputError(Exception): pass def validate_input(input_str): if not input_str.isalpha(): raise InvalidInputError("Input must contain only letters.") return True try: validate_input("123") except InvalidInputError as e: print(e)
Here, we define a custom exception InvalidInputError
and raise it in the validate_input
function if the input contains non-letter characters. The try
block attempts to validate the input, and the except
block catches the raised exception.
Built-in Exceptions
Here are some python built-in exceptions.
Exception | Description |
SyntaxError | Raised when the Python parser detects a syntax error. |
IndentationError | Raised when there is incorrect indentation. |
NameError | Raised when a local or global name is not found. |
TypeError | Raised when an operation or function is applied to an object of inappropriate type. |
ValueError | Raised when a function receives an argument of correct type but with an inappropriate value. |
ZeroDivisionError | Raised when the second operand of a division or modulo operation is zero. |
FileNotFoundError | Raised when a file or directory is requested but cannot be found. |
IndexError | Raised when a sequence subscript is out of range. |
KeyError | Raised when a dictionary key is not found. |
AttributeError | Raised when attribute reference or assignment fails. |
ImportError | Raised when an import statement fails to find the module definition. |
MemoryError | Raised when the interpreter runs out of memory. |
KeyboardInterrupt | Raised when the user presses Ctrl+C while the program is running. |
StopIteration | Raised by the next() function to signal that there are no further items produced by the iterator. |
OverflowError | Raised when the result of an arithmetic operation is too large to be represented. |
RuntimeError | Raised when an error is detected that doesn’t fall into any of the other categories. |
OSError | Base class for I/O-related errors. |