Python is one of the most popular programming languages, known for its simplicity and readability. However, even the most well-written code can face errors during execution. These errors, if not handled properly, can cause your program to crash. This is where exception handling comes into play.
In this article, weāll learn exception handling in Python. Weāll cover everything from basic concepts to advanced techniques, along with various practical examples.
What is Exception Handling?
Exception handling is a mechanism in Python that allows you to manage errors. Instead of letting your program crash, you can ācatchā these errors and take appropriate actions, such as logging the error, displaying a user-friendly message, or retrying the operation.
In Python, errors are broadly classified into two types:
- Syntax Errors: These occur when the code violates the rules of Python syntax. For example, forgetting a colon at the end of an if statement.
- Exceptions: These are runtime errors that occur during the execution of the program. Examples include dividing by zero, accessing a non-existent file, or trying to convert a string to an integer.
Basic Structure of Exception Handling in Python
Python provides three main keywords for exception handling:
- try: The block of code where you expect an exception to occur.
- except: The block of code that handles the exception.
- finally: An optional block that runs regardless of whether an exception occurred or not.
Hereās a simple example:
try: result = 10 / 0 # This will raise a ZeroDivisionError except ZeroDivisionError: print("Oops! You can't divide by zero.") finally: print("This will always execute.")
Output
Oops! You can't divide by zero. This will always execute.
Common Built-in Exceptions in Python
Python has a wide range of built-in exceptions. Here are some of the most common ones:
- ZeroDivisionError: Raised when dividing by zero.
- TypeError: Raised when an operation is performed on an inappropriate type.
- ValueError: Raised when a function receives an argument of the correct type but an inappropriate value.
- FileNotFoundError: Raised when a file or directory is requested but doesnāt exist.
- IndexError: Raised when trying to access an index that doesnāt exist in a list.
- KeyError: Raised when a dictionary key is not found.
- NameError: Raised when a variable is not found in the local or global scope.
- AttributeError: Raised when an attribute reference or assignment fails.
- ImportError: Raised when an imported module or name is not found.
Handling Multiple Exceptions
You can handle multiple exceptions in a single try
block by specifying multiple except
clauses. Hereās an example:
try: num = int(input("Enter a number: ")) result = 10 / num print("Result:", result) except ZeroDivisionError: print("Error: Division by zero is not allowed.") except ValueError: print("Error: Invalid input. Please enter a valid number.")
Output (if input is 0)
Error: Division by zero is not allowed.
Output (if input is āabcā)
Error: Invalid input. Please enter a valid number.
The else Clause in Exception Handling
The else
clause is executed if no exceptions are raised in the try
block. Itās useful for code that should run only when the try
block is successful.
try: num = int(input("Enter a number: ")) result = 10 / num except ZeroDivisionError: print("Error: Division by zero is not allowed.") else: print("Result:", result)
Output (if input is 2)
Result: 5.0
The finally Clause
The finally
block is executed no matter what, whether an exception occurs or not. Itās typically used for cleanup actions, such as closing files or releasing resources.
try: file = open("example.txt", "r") content = file.read() print(content) except FileNotFoundError: print("Error: File not found.") finally: file.close() print("File closed.")
Raising Exceptions Manually
Sometimes, you may want to raise an exception manually using the raise
keyword. This is useful when you want to enforce certain conditions in your code.
def check_age(age): if age < 0: raise ValueError("Age cannot be negative.") elif age < 18: print("You are a minor.") else: print("You are an adult.") try: check_age(-5) except ValueError as e: print(e)
Output
Age cannot be negative.
Custom Exceptions
Python allows you to define your own exceptions by creating a new class that inherits from the built-in Exception
class.
class NegativeNumberError(Exception): pass def check_positive(number): if number < 0: raise NegativeNumberError("Negative numbers are not allowed.") try: check_positive(-10) except NegativeNumberError as e: print(e)
Output
Negative numbers are not allowed.