How to properly handle exceptions in Python in various ways?
sobes.tech AI
Answer from AI
Exceptions are handled using try, except, else, finally blocks.
Main types of handling:
-
Basic catch: Catches any exception.
try: # Code that may raise an exception result = 10 / 0 except: # Handling any exception print("An error occurred.") -
Catching specific exception: Catches a particular type of exception.
try: # Code that may raise an exception result = 10 / 0 except ZeroDivisionError: # Handling division by zero print("Error: Division by zero.") -
Catching multiple exceptions: Catches multiple types of exceptions.
try: # Code that may raise an exception data = [1, 2, 3] print(data[5]) result = 10 / 0 except (IndexError, ZeroDivisionError): # Handling index errors or division by zero print("Indexing error or division by zero occurred.") -
Catching exception with access to exception object: Allows access to error information.
try: # Code that may raise an exception result = int("abc") except ValueError as e: # Handling type conversion error, e contains error info print(f"Value error: {e}") -
Using
else: Block executes if no exceptions occur intry.try: # Code without errors result = 10 / 2 except ZeroDivisionError: print("Error: Division by zero.") else: # Executes if no errors print(f"Result: {result}") -
Using
finally: Block always executes, regardless of exceptions. Often used for resource cleanup.file = None try: file = open("myfile.txt", "r") # Read from file or other operations except FileNotFoundError: print("File not found.") finally: # Ensures file is closed if it was opened if file: file.close() print("File closed.") -
raiseto raise exceptions: Used to generate exceptions.def divide(a, b): if b == 0: # Raise exception raise ZeroDivisionError("Cannot divide by zero!") return a / b try: print(divide(10, 0)) except ZeroDivisionError as e: print(f"Caught exception: {e}") -
raise ... from ...to chain exceptions: Allows linking a new exception with a previous one.try: result = 1 / 0 except ZeroDivisionError as e: # Raise new exception linked to previous raise RuntimeError("An internal error occurred") from e -
Using
with open(...)context manager: Ensures proper resource closing (e.g., file).try: with open("myfile.txt", "r") as file: content = file.read() print(content) # file automatically closes after with block except FileNotFoundError: print("File not found.")
Summary table of exception handling blocks:
| Block | Description | When executed |
|---|---|---|
try |
Code block where exceptions may occur | Always |
except |
Handles exceptions raised in try |
If an exception occurs |
else |
Executes if no exceptions in try |
If no exceptions |
finally |
Always executes, regardless of exceptions | Always |
Choosing the method depends on the specific situation and the level of error handling detail required. It is important to catch only those exceptions that can be properly handled and avoid overly broad catches (except:) unless necessary.