🟢 Beginner · Lesson 18
Exception Handling
What is an Exception?
An exception is an error that happens while a program runs (like dividing by zero). Without handling, the program crashes. Exception handling lets you catch the error and respond gracefully.
try / except
Python – tryexcept
try:
# risky code
risky_operation()
except SomeError:
# runs if that error happens
handle_it()Python tries the try block. If an error occurs, it jumps to the matching except instead of crashing.
Common Errors
| Error | Cause |
|---|---|
| ZeroDivisionError | Dividing by 0 |
| ValueError | int("abc") — wrong type of value |
| TypeError | "5" + 5 — mixing types |
| FileNotFoundError | Opening a missing file |
| IndexError | List index out of range |
Program 1: Safe Division
Python – divide.py
a = int(input("Numerator: "))
b = int(input("Denominator: "))
try:
print("Result:", a / b)
except ZeroDivisionError:
print("Error: cannot divide by zero")Numerator: 10
Denominator: 0
Error: cannot divide by zero
Without the try, dividing by 0 would crash the program. Now it prints a friendly message.
Program 2: Safe Number Input
Python – safeinput.py
try:
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)
except ValueError:
print("Please enter a valid number")Enter your age: hello
Please enter a valid number
If the user types text instead of a number, int() raises ValueError, which we catch.
Program 3: Multiple except + finally
Python – multi.py
try:
nums = [10, 20, 30]
i = int(input("Index: "))
print(nums[i])
except ValueError:
print("Index must be a number")
except IndexError:
print("Index out of range")
finally:
print("Done checking")Index: 5
Index out of range
Done checking
- Each
excepthandles a different error type. finallyalways runs — error or not — good for cleanup.
Raising Your Own Error
Use raise to signal an error yourself when input is invalid.
Python – raise.py
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
print("Age set to", age)
try:
set_age(-5)
except ValueError as e:
print("Caught:", e)Caught: Age cannot be negative
Common Mistakes
- Catching every error with a bare
except:— hides real bugs. - Putting too much code inside one
tryblock. - Forgetting that
finallyruns no matter what.
Practice Tasks
- Ask for two numbers and divide them safely.
- Keep asking for a number until the user enters a valid one.
- Open a file and handle FileNotFoundError nicely.
- Write a function that raises an error for a negative marks value.
Summary
- Exceptions are runtime errors; handling stops crashes.
tryruns risky code;exceptcatches specific errors.finallyalways runs;raisecreates your own error.
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.