⚠️ Exception Handling
Last Updated: 06 Sept 2025
- Exception = error that happens while running a program.
- Without handling → program crashes.
- With handling → program catches error and continues safely.
✏ Basic try-except
We use try and except block.
try:
x = 10 / 0 # division by zero
except ZeroDivisionError:
print("Cannot divide by zero!")
👉 Here, instead of crashing, it prints message.
Multiple except Blocks
a=10
b=2
try:
res=a/b
print(res)
except ZeroDivisionError:
print("Cannot divide by zero!")
except TypeError:
print("Type error")
except:
print("Any error")
Catching Any Exception
try:
result = 10 / 0
except Exception as e:
print("Error happened:", e)
👉 Exception as e gives the error message.
⚙ else with try-except
If there is no error, else block is executed.
try:
x = 5 / 1
except ZeroDivisionError:
print("Divide by zero error")
else:
print("Division successful:", x)
🧹 finally Block
finally block is always executed.Either error occurs or not.
a=10
b=2
try:
res=a/b
except ZeroDivisionError:
print("error")
except:
print("Any error")
else:
print(res)
finally:
print("Always RUN")
Custom Exceptions
We can raise our own exceptions using raise.
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or above")
print("Access granted")
try:
check_age(15)
except ValueError as e:
print("Error:", e)
👉 Here, we raise error if age is less than 18.
💡 Quick Practice
- Write a program to divide two numbers using try-except block.
- Exercises