Introduction
Python provides a powerful feature called Exception Handling, and the most commonly used part of exception handling is the try-except statement. The try-except block allows developers to detect errors and handle them gracefully without stopping the entire program.
Instead of displaying confusing error messages and terminating execution, a Python program can show meaningful messages, recover from errors, and continue running smoothly.
What is Python Try Except?
Python Try Except is a mechanism used to handle runtime errors (exceptions) in a program.
The code that might generate an error is placed inside the try block. If an exception occurs, Python immediately stops executing the try block and transfers control to the appropriate except block.
Example Without Try Except
num = 10
result = num / 0
print(result)
Output:
The program crashes because division by zero is not allowed.
Example With Try Except
try:
num = 10
result = num / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Output:
The program continues running safely.
Why Use Try Except?
Using Try Except provides several advantages:
- Prevents program crashes
- Improves user experience
- Makes applications more reliable
- Handles unexpected situations gracefully
- Helps with debugging
- Keeps programs running even when errors occur
In professional software development, exception handling is considered a best practice.
Syntax
The basic syntax of Try Except is:
try:
# Code that may cause an exception
except ExceptionType:
# Code to handle the exception
Example:
try:
number = int("abc")
except ValueError:
print("Invalid number")
Output:
How Try Except Works?
The execution flow follows these steps:
- Python executes the code inside the try block.
- If no exception occurs, the except block is skipped.
- If an exception occurs, Python stops the try block immediately.
- The matching except block executes.
- The program continues running.
Example:
try:
print("Start")
result = 10 / 0
print("End")
except ZeroDivisionError:
print("Error occurred")
Output:
Error occurred
Notice that “End” is never printed because execution stops when the exception occurs.
Handling ZeroDivisionError
A ZeroDivisionError occurs when dividing by zero.
Example:
try:
number = 100 / 0
except ZeroDivisionError:
print("Division by zero is not allowed")
Output:
Handling ValueError
A ValueError occurs when a function receives an invalid value.
Example:
try:
age = int("Python")
except ValueError:
print("Please enter a valid number")
Output:
Handling TypeError
A TypeError occurs when incompatible data types are used together.
Example:
try:
result = "10" + 5
except TypeError:
print("Cannot combine string and integer")
Output:
Handling IndexError
An IndexError occurs when accessing an invalid list index.
Example:
numbers = [10, 20, 30]
try:
print(numbers[5])
except IndexError:
print("Index out of range")
Output:
Handling KeyError
A KeyError occurs when a dictionary key does not exist.
Example:
student = {
"name": "John"
}
try:
print(student["age"])
except KeyError:
print("Key not found")
Output:
Handling Multiple Exceptions
A single block of code may generate different types of exceptions.
Example:
try:
number = int(input("Enter a number: "))
result = 100 / number
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero")
Possible Outputs:
or
Cannot divide by zero
Using Multiple Exceptions in One Except Block
You can handle multiple exceptions together.
Example:
try:
number = int(input())
result = 10 / number
except (ValueError, ZeroDivisionError):
print("Invalid operation")
Output:
Using a Generic Exception
The Exception class can catch almost all exceptions.
Example:
try:
result = 10 / 0
except Exception as e:
print("Error:", e)
Output:
The variable e contains the exception message.
Using Else with Try Except
The else block executes only if no exception occurs.
Syntax
try:
pass
except:
pass
else:
pass
Example:
try:
number = int(input("Enter a number: "))
except ValueError:
print("Invalid input")
else:
print("Number entered:", number)
Input:
25
Output:
Using Finally with Try Except
The finally block always executes whether an exception occurs or not.
Example:
try:
result = 10 / 2
except ZeroDivisionError:
print("Error")
finally:
print("Program completed")
Output:
This is useful for cleanup operations.
Complete Example
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 / num2
except ValueError:
print("Please enter valid numbers")
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result:", result)
finally:
print("Calculation finished")
Input:
20
5
Output:
Calculation finished
Try Except with File Handling
File operations often generate exceptions.
Example:
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("File not found")
Output:
This prevents the application from crashing when files are missing.
Real-life Example
Imagine you are building an online banking application.
Users can withdraw money from their accounts.
balance = 5000
try:
amount = int(
input("Enter withdrawal amount: ")
)
if amount > balance:
raise ValueError(
"Insufficient balance"
)
balance -= amount
print("Withdrawal successful")
except ValueError as e:
print(e)
Input:
7000
Output:
Common Mistakes
1. Not Using Try Except
Incorrect:
result = 10 / 0
Output:
Correct:
try:
result = 10 / 0
except ZeroDivisionError:
print("Error")
2. Using a Generic Except Unnecessarily
Incorrect:
try:
pass
except:
print("Error")
Correct:
except ValueError:
print("Invalid value")
Specific exceptions are easier to debug.
3. Ignoring Error Messages
Incorrect:
except Exception:
print("Error")
Correct:
except Exception as e:
print(e)
Provides more useful information.
4. Putting Too Much Code in Try Block
Incorrect:
try:
# Hundreds of lines
Correct:
try:
result = num1 / num2
Keep try blocks focused on risky code.
5. Forgetting Finally for Cleanup
Incorrect:
try:
file = open("data.txt")
except:
pass
Better:
finally:
print("Resources released")
Best Practices
1. Use Specific Exceptions
except ValueError:
More readable and maintainable.
2. Keep Try Blocks Small
Place only error-prone code inside the try block.
3. Use Meaningful Error Messages
print("Please enter a valid number")
Helps users understand the problem.
4. Log Errors in Large Applications
Store exception information for troubleshooting.
5. Use Finally for Cleanup
finally:
print("Cleanup completed")
Ensures resources are released properly.
Difference Between Try Except Blocks
| Block | Purpose |
|---|---|
| try | Contains risky code |
| except | Handles exceptions |
| else | Executes if no exception occurs |
| finally | Always executes |
Conclusion
Python Try Except is one of the most important tools for handling errors and building reliable applications. It allows developers to catch exceptions, display meaningful messages, and prevent programs from crashing unexpectedly.
By using try, except, else, and finally, you can create applications that handle unexpected situations gracefully. Whether you are working with user input, mathematical calculations, files, databases, or web applications, proper exception handling improves stability, debugging, and user experience.