Introduction
Even the best programs encounter problems - missing files,
invalid input, or unexpected values. Without error handling, these issues can
crash your program. Python provides a powerful system of exceptions to
detect and manage errors gracefully. In this tutorial, we’ll learn how to use
try, except, finally, and raise to build robust programs.
Step 1: What Are Exceptions?
An exception is an error that occurs during program
execution. For example:
Code-1:
print(10 / 0)
Output:
ZeroDivisionError: division by zero
Without handling, the
program stops immediately.
Code-2
num =
int("Hello")
print(num)
Output:
ValueError: invalid literal for int() with base 10: 'Hello'
Step 2: Using try and except
You can catch exceptions using try and except.
Code-1
try:
print(10/0)
except ZeroDivisionError:
print("0 cannot
divide any number")
Output:
0 cannot divide any number
Code-2
num =
int("Hello")
print(num)
except ValueError:
print("Invalid Input, Enter a number")
- Code
inside try runs normally.
- If
an error occurs, Python jumps to the except block.
Output:
Invalid Input, Enter a number
Step 3: Handling Multiple Exceptions
You can handle different errors separately.
try:
file =
open("data.txt", "r")
content =
file.read()
except FileNotFoundError:
print("File not
found!")
except PermissionError:
print("Permission denied!")
Since file is not available in folder.
This makes your program more specific and user-friendly.
Step 4: Using finally
The “finally” block runs no
matter what — useful for cleanup tasks.
Code:
try:
file =
open("data.txt", "r")
content =
file.read()
except FileNotFoundError:
print("File not
found!")
finally:
print("Closing
program...")
Even if an error occurs, "Closing
program..." will always print.
Step 5: Raising Exceptions
You can raise your own exceptions with raise.
Code:
def check_age(age):
if age < 0:
raise
ValueError("Age cannot be negative!")
return age
print(check_age(25))
print(check_age(-5)) #
Raises ValueError
This is useful for enforcing rules in your program.
Step 6: Combining Everything
Here’s a complete example:
Code:
try:
num =
int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("That was
not a valid number.")
except ZeroDivisionError:
print("Cannot
divide by zero!")
else:
print("Result
is:", result)
finally:
print("Program
finished.")
- else runs if no exception occurs.
- finally runs regardless of success or failure.
Mini Exercise
Try this challenge:
- Write
a function divide(a, b) that divides two
numbers.
- Handle
ZeroDivisionError if b is zero.
- Handle
TypeError if inputs are not numbers.
- Print
a friendly message in each case.
Hint:
def divide(a, b):
try:
return a / b
except
ZeroDivisionError:
print("Error: Cannot divide by zero.")
except TypeError:
print("Error: Inputs must be numbers.")
print(divide(10,
2)) # Output: 5.0
print(divide(10,
0)) # Error message
print(divide("10", 2)) # Error message
Conclusion
In this tutorial, you learned how to:
- Catch
exceptions with try and except
- Handle
multiple types of errors
- Use
finally for cleanup tasks
- Raise
your own exceptions
- Build
robust programs with complete error handling
Error handling is the safety net of Python
programming. It ensures your programs don’t crash unexpectedly and provides
clear feedback to users.
In the next tutorial, we’ll explore Basics of Object-Oriented
Programming (OOP).







