- Home
- /
- Python try…except
Python Tutorial
Introduction
Python Data Types & Oper...
Python Strings
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Python Loops
Python Functions
Python Modules
Python OOPS
Advanced Topics
File Handling
- Home
- /
- Python try…except
Python try...except
Sometimes, your program may face unexpected errors—like dividing by zero or getting a string instead of a number. That’s where exception handling helps. Python uses the try
, except
, else
, and finally
blocks to catch and manage errors without crashing the program..
try...except Block
The try
block runs code that might cause an error.
If an error occurs, Python skips the rest of the try
block and jumps to the except
block.
try:
age = int(input("Enter your age: "))
except ValueError:
print("Please enter a valid number.")
Output:
Enter your age: twenty
Please enter a valid number.
try...except...else Block
If no error happens in the try
block, the else
block runs.
try:
marks = int(input("Enter your marks: "))
except ValueError:
print("Marks must be a number.")
else:
print("You entered:", marks)
Output Example 1:
Enter your marks: 87
You entered: 87
Output Example 2:
Enter your marks: eighty seven
Marks must be a number.
try...except...finally Block
The finally
block always runs, no matter what happened before—whether an error occurred or not.
try:
num = int(input("Enter a number: "))
except ValueError:
print("That’s not a number.")
else:
print("Thanks for entering:", num)
finally:
print("End of try-except example.")
Output Example 1:
Enter a number: 15
Thanks for entering: 15
End of try-except example.
Output Example 2:
Enter a number: fifteen
That’s not a number.
End of try-except example.
Summary
Use
try
to run code that may raise errors.Use
except
to handle specific errors.Use
else
to run code only when no error occurs.Use
finally
for cleanup tasks—runs no matter what.
This makes your Python programs more stable and user-friendly, especially when dealing with inputs, files, or external data.