What Is Try and Except?
In Python, the try and except is like a safety mechanism that allows your program to handle mistakes easily without crashing the whole code.
We all know, Python faces an error, and the program stops immediately. But the real projects, like apps, websites, and scripts, always need to be run. We don’t want our platform are suddenly crash.
The try…except helps to:
- Prevent program crashes
- Show user-friendly messages
- Continue execution even after an error
Basic Syntax of try…except Blocks
try:
# Code that might raise an exception
risky_code()
except:
# Code to handle the exception
handle_error()
How try…except works?
- Python first runs the code inside the try block.
- If everything is ok (no errors) → except is skipped.
- If an error occurs, Python immediately stops executing the try block and jumps to the except block.
- After the exception block handling (error) and the program continues execution.
Examples of try and except
Let’s write the basic example so we can know how to actually try…except it works.
def divide_numbers(a, b):
try:
result = a / b
print("Result is:", result)
except:
print("Oops! Division failed because the second number is zero.")
divide_numbers(10, 2)
divide_numbers(10, 0)
Output:
Result is: 5.0
Oops! Division failed because the second number is zero.
Explanation:
- First call → 10 / 2 works fine
- Second call → 10 / 0 causes an error
- Instead of crashing, Python shows a friendly message
- The program handled the error and keeps running
How Can We Handle Specific Exceptions?
Handling specific exceptions means you tell Python I’m expecting this exact error and want to handle it safely.
Your program is not crashing when something goes wrong; instead, Python gives you a chance to respond politely to the mistake and continue running.
This method refers to a pre-planning strategy, which means you try something risky, and if a problem happens, you already know what to do.
Why We Catch a Specific Exception?
If you catch all errors blindly, you may hide real bugs. Catching a specific error keeps your program:
- easy to debug
- clean
- safe
Example of Specific Exception
A user enters how many cups of tea they drink daily. If they enter text instead of a number, we handle only that mistake.
try:
cups = int(input("How many cups of tea do you drink per day? "))
print("Tea cups recorded:", cups)
except ValueError:
print("Please enter numbers only, not words.")
Output (if user inputs a non-integer):
Please enter numbers only, not words.
How This Code Works?
- int() tries to convert user input into a number
- If the user types text, Python raises ValueError
- except ValueError: catches only this error, and the program does not crash
How To Use Multiple except Blocks
Multiple except blocks are useful when different types of errors can happen in the same code, and you want to handle each error with a specific message.
Sometimes, one mistake can be a wrong input, another mistake can be an invalid calculation, so you need different solution. Because if we use only one except, we won’t know exactly what went wrong in the code.
Example of Multiple except Blocks
Imagine a movie ticket counter:
- User must enter number of tickets
- Each ticket costs ₹150
- If user enters wrong data → show proper message
try:
tickets = int(input("How many tickets do you want? "))
price = 150
total = price * tickets
print("Total amount to pay: ₹", total)
except ValueError:
print("Please enter a valid number for tickets.")
except TypeError:
print("Something went wrong with the calculation.")
In this code:
- The try block takes input from the user, converts it to a number, and calculates the total price.
- except ValueError runs only if the user enters text like “three” instead of
3 - except TypeError handles unexpected calculation issues.
How To Use else with try…except
The else block with try…except is used to run code only when no error occurs in the try block.
If any exception happens, the else block is skipped completely.
- try = risky work
- except = error handling
- else = success path
Simple Example:
Let’s build a mobile recharge calculator where:
- User enters recharge amount
- GST is added
- Errors are handled properly
try:
amount = int(input("Enter recharge amount: ₹"))
final_amount = amount + (amount * 0.18)
except ValueError:
print("Please enter numbers only.")
else:
print("Recharge successful!")
print("Amount after GST: ₹", final_amount)
Output will this:
#input
Enter recharge amount: ₹100
#output:
Recharge successful!
Amount after GST: ₹ 118.0
Invalid Non-Numeric) Input:
#input:
Enter recharge amount: ₹abc
#Output:
Please enter numbers only.
How To Use finally with try…except
In Python, errors can happen at runtime. For example, a missing file, wrong input, or a broken connection.
The try…except…finally structure is Python’s safe way to handle these situations without crashing the program.
The finally block is useful when some code runs in all situations, whether errors happen or not. like:
- closing files
- releasing memory
- disconnecting databases
- stopping sensors or devices
Example Code:
If you open a notebook, whether you read it successfully or not, you must close it properly.
try:
book = open("notes.txt", "r")
text = book.read()
print("Notes content:")
print(text)
except FileNotFoundError:
print("Notes file is missing!")
finally:
if 'book' in locals():
book.close()
print("Notebook closed safely.")
Explanation of the code:
- try block trying to read the file
- except runs only if file is missing
- finally always closes the file
How To Use Nested try…except Blocks?
In large projects, a single try…except block is not enough to handle all types of errors clearly. In this case, we are using nested blocks, which means one try…except block inside another.
Nested try…except is useful when:
- One operation depends on another
- Different errors need different handling
- You want clearer error messages for students or users
- You want better control over program flow
Example:
In this code example:
- The outer try checks user input
- The inner try checks calculation logic
- Each error is handled at the correct level
try:
user_input = input("Enter total marks: ")
try:
marks = int(user_input)
percentage = marks / 5
print("Your percentage is:", percentage)
except ZeroDivisionError:
print("Calculation error: Total marks cannot be zero.")
except ValueError:
print("Input error: Please enter numbers only.")
Output In Multiple Scenario:
# If user enters: abc
Input error: Please enter numbers only.
# If user enters: 0
Calculation error: Total marks cannot be zero.
# If user enters: 450
Your percentage is: 90.0
Common Exceptions in Python
Here are some common exceptions you may encounter:
| Exception | Description |
|---|---|
| ValueError | This error occurs when the user inserts the wrong value type. |
| ZeroDivisionError | Occurs when a number is divided by zero, which is not allowed in mathematics. |
| FileNotFoundError | This will happen when Python cannot find the file you are trying to open. |
| TypeError | Occurs when an operation is performed on data types that do not work together. |
| IndexError | This error happens when you try to access a specific position that does not exist in a list or tuple. |
Also Read Other Topics:
- What is RegEx in Python?
- Python JSON (JavaScript Object Notation)
- What is the math module in Python?
- What are dates in Python?
- What is a scope in Python?

M.Sc. (Information Technology). I explain AI, AGI, Programming and future technologies in simple language. Founder of BoxOfLearn.com.