In Python, an exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
When an exception occurs, it is typically represented as an object that contains information about the error, such as its type and a message describing the error.
Python provides a robust exception handling mechanism that allows us to handle exceptions gracefully, preventing our program from crashing and providing opportunities to recover from errors.
We can handle exceptions using the try, except, else, and finally blocks.
try: # Code that may raise an exception result = 30 / 0 except ZeroDivisionError: # Handle the specific exception print("Error: Division by zero!") else: # Executes if no exception occurred print("No exception occurred!") finally: # Executes regardless of whether an exception occurred or not print("Finally block executed.")
We can catch multiple exceptions by providing multiple except blocks or by using a tuple of exception types:
try: # Code that may raise an exception result = int(input("Enter a number: ")) / 0 except (ValueError, ZeroDivisionError): # Handle multiple exceptions print("Invalid input or division by zero!")
We can explicitly raise exceptions using the raise statement:
x = -1 if x < 0: raise ValueError("x cannot be negative")
We can define custom exception classes by inheriting from the Exception class or one of its subclasses:
class YourCustomError(Exception): pass try: raise YourCustomError("An error occurred") except YourCustomError as e: print(e)
Exceptions propagate up the call stack until they are caught by an appropriate except block.
If an exception is not caught, the program terminates and prints a traceback.
Python has a rich hierarchy of built-in exception types.
Some common built-in exceptions include TypeError, ValueError, ZeroDivisionError, IndexError, KeyError, and IOError, among others.
The primary goal of exception handling is to gracefully handle errors and ensure that the program does not crash unexpectedly.
This may involve logging the error, providing informative error messages to the user, or attempting to recover from the error and continue execution.
try: # Code that may raise an exception data = open("nonexistent_file.txt", "r") except FileNotFoundError: # Handle the specific exception print("Error: File not found!")
Exception handling is an essential aspect of writing robust and reliable Python code.
It allows us to anticipate and handle potential errors, making our programs more resilient in the face of unexpected conditions.