What happens when your program runs into an error?
Without preparation… it just stops.
And that’s not something real applications can afford.
So far, we’ve learned how to write programs that store data, make decisions, repeat actions, and even work with files.
But in real life, things don’t always go as expected.
Users enter wrong input, files may be missing, or calculations may fail.
That’s where exception handling comes in.
🔹 What is an Exception?
An exception is an error that occurs while a program is running.
For example:
print(10 / 0)
This causes an error because you cannot divide by zero.
Without handling it, the program crashes immediately.
🔹 Using Try and Except
Python allows us to handle errors using try and except.
try:
print(10 / 0)
except:
print("Something went wrong")
Instead of crashing, the program handles the error gracefully.
🔹 Handling Specific Errors
You can also handle specific types of errors.
try:
number = int(input("Enter a number: "))
print(10 / number)
except ZeroDivisionError:
print("You cannot divide by zero")
except ValueError:
print("Please enter a valid number")
Now the program knows exactly what went wrong.
🔹 Finally Block
There is also a finally block that always runs.
try:
print("Trying something...")
except:
print("Error occurred")
finally:
print("This will always run")
This is often used for cleanup actions like closing files.
💡 Why Exception Handling Matters
Exception handling makes your program:
- More stable
- More user-friendly
- Less likely to crash
- Ready for real-world use In real applications, errors are not avoided they are managed.
🌱 Challenge
Write a program that:
- Asks the user to enter a number
- Divides 100 by that number
- Handles:
- Zero division error
- Invalid input error Make sure your program never crashes, no matter what is entered.
Next, we’ll explore date and time, where your programs learn how to work with real-world time-based data like schedules and timestamps.
Top comments (0)