Error Handling & Exception Handling in Python 🚀🐍

Errors are inevitable in programming, and exception handling helps prevent crashes by managing errors gracefully.
1️⃣ What is Exception Handling?
An exception is an error that occurs during program execution. If not handled, it stops the program.
🔹 Example of an Unhandled Exception:
print(10 / 0) # ZeroDivisionError: division by zero
🔹 The program crashes if an exception is not handled.
✅ Solution: Use try-except blocks!
2️⃣ Basic Exception Handling with try-except
✅ Handling a Single Exception
try:
x = 10 / 0 # This causes an error
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
🔹 Output:
Error: Cannot divide by zero!
✔ The program does not crash because the error is caught.
3️⃣ Handling Multiple Exceptions
✅ Catching Multiple Error Types
try:
num = int("abc") # This will cause a ValueError
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input: Expected a number!")
🔹 Output:
less
Copy
Edit
Invalid input: Expected a number!
✔ Python checks each except block in order and runs the first matching one.
4️⃣ Using except Exception (Catching Any Error)
try:
num = int("abc") # ValueError
x = 10 / 0 # ZeroDivisionError
except Exception as e:
print(f"An error occurred: {e}")
🔹 Output:
An error occurred: invalid literal for int() with base 10: 'abc'
✔ Exception is the base class for all errors.
5️⃣ else and finally Blocks
Block Purpose
try Code that may cause an error
except Handle the error
else Runs only if no exception occurs
finally Runs always, even if an error occurs
✅ Using else and finally
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input!")
else:
print(f"Result: {result}") # Runs only if no error
finally:
print("Execution completed.") # Always runs
✔ The finally block closes resources (like files, databases).
6️⃣ Raising Exceptions with raise
You can manually raise 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!
7️⃣ Summary
Concept Description
try block Code that may cause an error
except block Handles specific exceptions
Multiple except blocks Catch different error types
except Exception Catches all exceptions
else block Runs if no error occurs
finally block Always runs (cleanup code)
raise Manually throw an exception
Date: 2025-03-24 00:00:00.000000