When I started writing Python programs, getting an error was frustrating.
I would run my program and suddenly see a long error message in the terminal.
At first, I just wanted the error to disappear.
Then I realised that errors are actually useful because they tell me something went wrong.
The next question was: how can I make my programs handle these situations without crashing?
That's where exception handling came in.
What is an exception?
An exception is an error that happens while a program is running.
For example, this will cause an error:
number = int(input("Enter a number: "))
If I enter:
hello
Python can't convert "hello" into an integer, so the program crashes.
Instead of letting that happen, I can handle the error.
try and except
The basic structure is try and except.
For example:
try:
number = int(input("Enter a number: "))
print(number)
except ValueError:
print("Please enter a valid number.")
Now if I enter:
hello
I get:
Please enter a valid number.
The program doesn't suddenly stop.
This was probably the first time exception handling really made sense to me.
A practical example
Imagine I'm creating a simple division program.
Normally:
number = int(input("Enter a number: "))
divisor = int(input("Enter the divisor: "))
result = number / divisor
print(result)
But what happens if the user enters 0 as the divisor?
Python raises a ZeroDivisionError.
I can handle it:
try:
number = int(input("Enter a number: "))
divisor = int(input("Enter the divisor: "))
result = number / divisor
print(result)
except ZeroDivisionError:
print("You cannot divide by zero.")
Now the program can respond properly instead of crashing.
Handling different errors
A program can have more than one possible error.
For example:
try:
number = int(input("Enter a number: "))
divisor = int(input("Enter the divisor: "))
print(number / divisor)
except ValueError:
print("Please enter numbers only.")
except ZeroDivisionError:
print("You cannot divide by zero.")
Now Python can handle each problem differently.
That helped me understand that except isn't just about saying "something went wrong."
I can tell Python what kind of problem I expect and what I want it to do about it.
else
else runs when no exception occurs.
For example:
try:
number = int(input("Enter a number: "))
except ValueError:
print("Invalid number.")
else:
print(f"You entered {number}.")
So:
Correct input → else runs.
Invalid input → except runs.
I found this useful when I wanted to separate successful code from error-handling code.
finally
finally runs whether there is an error or not.
For example:
try:
file = open("notes.txt", "r")
print(file.read())
except FileNotFoundError:
print("The file does not exist.")
finally:
print("Finished attempting to read the file.")
The finally block will always run.
This is useful when there is something I need to do regardless of whether the operation succeeded.
A file example
Since I had already learnt file handling, this was one of the easiest ways for me to understand exception handling.
Imagine I try to open a file that doesn't exist:
try:
with open("contacts.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("Contacts file not found.")
Instead of getting a long traceback, my program can give the user a clear message.
raise
Sometimes I don't want to wait for Python to generate an error.
I can create an exception myself using raise.
For example, suppose I don't want negative ages:
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative.")
print(age)
This lets me create my own rule and stop the program when that rule is broken.
A practical validation example
Suppose I'm creating a simple registration system.
I want the user to be at least 18:
age = int(input("Enter your age: "))
if age < 18:
raise ValueError("You must be at least 18 years old.")
print("Registration successful.")
I'm now checking for a condition that matters to my program rather than just relying on Python to find a technical error.
What I understood
The biggest thing I learnt is that exception handling isn't about hiding errors.
It's about deciding how my program should respond when something unexpected happens.
I started thinking about it like this:
try → "Try this code."
except → "If this specific problem happens, handle it like this."
else → "If everything worked, do this."
finally → "Do this no matter what."
raise → "I want to create an error because this situation isn't acceptable."
Final thoughts
At first, errors made me feel like my code was completely wrong.
Now I see them differently.
Some errors are simply situations my program needs to be prepared for.
A user might enter the wrong type of data.
A file might not exist.
Someone might try to divide by zero.
A value might break a rule in my program.
Exception handling gives me a way to deal with those situations without making the whole program fall apart.
That was an important shift for me: a good program isn't one where errors never happen. It's one that knows how to handle them.
Top comments (0)