Exception Handling in Python – Managing Errors Gracefully
Introduction
Errors are part of programming — no matter how perfect your code seems.
In Python, when an error occurs during execution, the program stops and shows an error message.
But with exception handling, you can catch and manage these errors smoothly.
1. What Is an Exception?
An exception is an error that occurs during program execution, disrupting the normal flow.
Examples include:
-
ZeroDivisionError
– dividing by zero -
ValueError
– invalid input -
FileNotFoundError
– missing file
2. Basic try–except Block
Example:
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print("Result =", a / b)
except ZeroDivisionError:
print("You can’t divide by zero!")
Output:
Enter a number: 10
Enter another number: 0
You can’t divide by zero!
3. Handling Multiple Exceptions
try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input. Please enter a number.")
Output:
Invalid input. Please enter a number.
4. Using else Block
The else
block runs only if no error occurs.
try:
num = int(input("Enter a number: "))
print("Square =", num * num)
except ValueError:
print("Please enter a valid number.")
else:
print("Execution successful!")
Output:
Enter a number: 5
Square = 25
Execution successful!
5. Using finally Block
The finally
block always executes — useful for closing files or releasing resources.
try:
f = open("demo.txt", "w")
f.write("Learning Python Exception Handling")
finally:
f.close()
print("File closed successfully.")
Output:
File closed successfully.
6. Raising Exceptions Manually
You can raise an exception intentionally using the raise
keyword.
x = -1
if x < 0:
raise ValueError("Negative numbers not allowed!")
Output:
ValueError: Negative numbers not allowed!
7. Common Built-in Exceptions
Exception | Description |
---|---|
ZeroDivisionError |
Divide by zero |
ValueError |
Wrong type of value |
FileNotFoundError |
File doesn’t exist |
TypeError |
Wrong data type |
IndexError |
Invalid index |
KeyError |
Missing key in dictionary |
8. Nested try–except Example
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
try:
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Division by zero error!")
except ValueError:
print("Invalid input!")
Challenge for You
Write a program that:
-
Takes two numbers as input
-
Prints their division result
-
Handles both
ValueError
andZeroDivisionError
gracefully
Final Thoughts
- Exceptions make your program robust
- Use
try–except
to prevent crashes finally
helps you clean up resources- Use
raise
to customize error messages
In the next lesson, we’ll cover Object-Oriented Programming (OOP) in Python, one of the most powerful concepts in modern coding.
Comments
Post a Comment