Try-Except Blocks & Handling Specific Exceptions in Python ๐๐

Pythonโs try-except blocks allow you to handle errors gracefully without crashing the program.
1๏ธโฃ Basic try-except Block
๐น Without error handling, an error stops the program:
print(10 / 0) # ZeroDivisionError: division by zero
โ
Solution: Use try-except to handle the error
try:
print(10 / 0)
except:
print("An error occurred!")
๐น Output:
An error occurred!
โ The program continues running instead of crashing.
2๏ธโฃ Handling Specific Exceptions
๐น Instead of catching all errors, handle specific ones:
try:
x = int("abc") # This causes a ValueError
except ValueError:
print("Error: Invalid number!")
๐น Output:
Error: Invalid number!
โ This ensures that only expected errors are handled.
3๏ธโฃ Catching Multiple Exception Types
๐น Use multiple except blocks to handle different errors separately:
try:
num = int(input("Enter a number: ")) # Might cause ValueError
result = 10 / num # Might cause ZeroDivisionError
except ValueError:
print("Error: Please enter a valid number!")
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
๐น Example Runs:
Enter a number: abc
Error: Please enter a valid number!
vbnet
Copy
Edit
Enter a number: 0
Error: Cannot divide by zero!
โ Each error type has its own response.
4๏ธโฃ Catching Multiple Errors in One except Block
๐น If multiple errors need the same handling, use a tuple:
try:
num = int("abc") # ValueError
result = 10 / 0 # ZeroDivisionError
except (ValueError, ZeroDivisionError):
print("Error: Invalid input or division by zero!")
๐น Output:
Error: Invalid input or division by zero!
โ Shorter and cleaner than using multiple except blocks.
5๏ธโฃ Catching All Exceptions (Exception)
๐น Use Exception to catch any error (not recommended for all cases):
try:
x = int("xyz") # Causes ValueError
except Exception as e:
print(f"An error occurred: {e}")
๐น Output:
An error occurred: invalid literal for int() with base 10: 'xyz'
โ Exception is the base class for all errors, so it catches everything.
6๏ธโฃ Using else and finally
Block Purpose
try Code that may cause an error
except Handles the error
else Runs only if no exception occurs
finally Runs always, even if an error occurs
โ
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid number!")
else:
print(f"Success! The result is {result}")
finally:
print("Execution complete.")
โ else runs only if try succeeds.
โ finally always runs, useful for cleanup (e.g., closing files).
7๏ธโฃ Raising Exceptions (raise)
๐น You can manually trigger an exception using raise:
def check_age(age):
if age < 18:
raise ValueError("You must be 18 or older!")
print("Access granted.")
try:
check_age(16)
except ValueError as e:
print(f"Error: {e}")
๐น Output:
Error: You must be 18 or older!
8๏ธโฃ Summary
Concept Description
Basic try-except Handles errors to prevent crashes
Specific Exceptions except ValueError:, except ZeroDivisionError:
Multiple except Blocks Handle different errors separately
Multiple Errors in One except except (TypeError, ValueError):
Catching All Errors except Exception as e: (Use cautiously)
else Block Runs if no error occurs
finally Block Runs always (cleanup code)
Raising Exceptions raise ValueError("Custom error")
Date: 2025-03-24 00:00:00.000000