Exception Handling in Python


⚠️ Exception Handling in Python

Description: Understand how to manage errors gracefully in Python programs using structured exception handling.


1. Handling Multiple Exceptions

Python allows handling multiple exceptions using multiple except blocks or a single except block with a tuple of exceptions.

try: num = int(input("Enter a number: ")) result = 10 / num except ValueError: print("Invalid input. Please enter a number.") except ZeroDivisionError: print("Cannot divide by zero.") else: print("Result is:", result)

Explanation: This code prompts the user to enter a number and attempts to divide 10 by that number. It handles two specific exceptions: ValueError if the input is not a number, and ZeroDivisionError if the input is zero. If no exception occurs, it prints the result.



2. Using finally for Cleanup

The finally block is executed regardless of whether an exception occurs, making it ideal for cleanup actions.

try: file = open("example.txt", "r") content = file.read() print(content) except FileNotFoundError: print("File not found.") finally: file.close() print("File closed.")

Explanation: This code attempts to open and read a file. If the file is not found, it catches the FileNotFoundError. Regardless of the outcome, the finally block ensures that the file is closed properly.



3. Raising Exceptions Manually

You can raise exceptions manually using the raise statement to enforce certain conditions.

age = int(input("Enter your age: ")) if age < 0: raise ValueError("Age cannot be negative.")

Explanation: This code prompts the user to enter their age. If the entered age is negative, it raises a ValueError to indicate invalid input.



4. Creating Custom Exceptions

Custom exceptions can be created by defining a new class that inherits from the built-in Exception class.

class NegativeAgeError(Exception): pass try: age = int(input("Enter your age: ")) if age < 0: raise NegativeAgeError("Age cannot be negative.") except NegativeAgeError as e: print(e)

Explanation: This code defines a custom exception NegativeAgeError and raises it if the user enters a negative age. The exception is then caught and handled appropriately.



5. Nested try-except Blocks

Python allows nesting of try-except blocks to handle exceptions at different levels of code execution.

try: try: num = int(input("Enter a number: ")) result = 10 / num except ZeroDivisionError: print("Cannot divide by zero.") except ValueError: print("Invalid input.")

Explanation: This code demonstrates nested try-except blocks, where the inner block handles division by zero, and the outer block handles invalid input.



6. Using else with try-except

The else block can be used to execute code if no exceptions are raised in the try block.

try: num = int(input("Enter a number: ")) result = 100 / num except ZeroDivisionError: print("You can't divide by zero!") else: print("The result is:", result)

Explanation: If no exception occurs in the try block, the else block will execute. This is useful for separating error-handling logic from the main logic.



7. Handling Multiple Exceptions in One Line

You can also handle different exceptions using a single except block with a tuple.

try: num = int(input("Enter a number: ")) result = 10 / num except (ValueError, ZeroDivisionError) as e: print("Error occurred:", e)

Explanation: This code catches both ValueError and ZeroDivisionError using one except block, and prints the error message accordingly.



8. Try-Except Inside a Function

Exception handling can be integrated inside functions to create more robust programs.

def divide(x, y): try: result = x / y except ZeroDivisionError: print("Cannot divide by zero.") else: print("Result is:", result) divide(10, 2) divide(5, 0)

Explanation: This function handles division and protects against division by zero using a try-except block inside a function.



9. Using Assertions with Exception Handling

Assertions can be used to enforce conditions and raise exceptions if conditions are false.

def set_age(age): assert age >= 0, "Age cannot be negative." print("Age is valid.") set_age(25) set_age(-1)

Explanation: The assert statement checks if the condition is true. If not, it raises an AssertionError. Here, it's used to ensure age is not negative.



10. Logging Exceptions

You can use the logging module instead of print() to keep track of errors.

import logging try: open("nonexistentfile.txt") except FileNotFoundError as e: logging.error("File not found: %s", e)

Explanation: The logging module provides a way to log error messages, which is more flexible and robust than printing to the console, especially for large applications.


Summary:

  • try-except helps catch and handle errors.
  • finally always runs, great for cleanup.
  • raise is used to manually trigger errors.
  • Custom exceptions make error handling more descriptive.
  • Assertions are useful for debugging.