How do you handle exceptions in Python
In Python, exceptions are handled using a try-except
block to gracefully manage errors and prevent program crashes. Here’s how it works:
Basic Syntax:
python
try: # Code that might raise an exception result = 10 / 0 # Division by zero (will raise ZeroDivisionError) except ZeroDivisionError: # Code to handle the exception print("Cannot divide by zero!")
Key Components:
try
block:Contains the code that might raise an exception.
If an exception occurs, the rest of the
try
block is skipped.
except
block:Catches and handles specific exceptions (e.g.,
ValueError
,TypeError
).You can catch multiple exceptions or use a generic
Exception
.
else
block (optional):Runs only if no exceptions occur in the
try
block.
finally
block (optional):Always executes, whether an exception occurred or not (e.g., for cleanup like closing files).
Example with All Blocks:
try: num = int(input("Enter a number: ")) # Possible ValueError result = 10 / num # Possible ZeroDivisionError except ValueError: print("Invalid input! Please enter a number.") except ZeroDivisionError: print("Cannot divide by zero!") else: print(f"Result: {result}") # Runs if no exception finally: print("Execution complete.") # Always runs
Common Practices:
Catch specific exceptions (avoid bare
except:
):except (ValueError, TypeError) as e: # Catch multiple exceptions print(f"Error: {e}")
Get the exception details:
except Exception as e: print(f"An error occurred: {e}")
Raise custom exceptions:
if x < 0: raise ValueError("Negative values are not allowed!")
Use
finally
for resource cleanup:file = open("example.txt", "r") try: content = file.read() finally: file.close() # Ensures the file is always closed
Built-in Exceptions (Common Ones):
ValueError
: Invalid value (e.g.,int("abc")
).TypeError
: Incorrect type (e.g.,"hello" + 5
).IndexError
: List index out of range.KeyError
: Dictionary key not found.FileNotFoundError
: File does not exist.
Why Use Exception Handling?
Prevents abrupt program termination.
Improves debugging with meaningful error messages.
Ensures resources are released properly (e.g., files, connections)