try & except in Python
Learn how to handle exceptions using Python's
try and except blocks.
What are try and except?
The try and except blocks
are used to handle exceptions in Python.
Code that may cause an exception is placed inside
the try block.
If an exception occurs, Python moves to the
matching except block.
try contains risky code and
except handles the error.
try & except Flow
try Block
Python executes the code that may cause an exception.
No Exception
Program continues normally.
Exception Occurs
Control moves to the matching except block.
except Block
The exception is handled and the program can continue.
Basic Syntax
try:
# code that may cause an exception
except:
# code to handle the exception
The try block must be followed by
an except block.
Simple Example
try:
number = 10 / 0
print(number)
except:
print("An error occurred")
Output:
An error occurred
The division causes an exception, so Python executes
the except block.
Handling a Specific Exception
It is better to catch the specific exception that we expect.
try:
number = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Output:
Cannot divide by zero
Here we specifically handle
ZeroDivisionError.
Handling ValueError
A ValueError can occur when a value
is not valid for an operation.
try:
age = int("abc")
print(age)
except ValueError:
print("Please enter a valid number")
Output:
Please enter a valid number
Handling TypeError
try:
result = "10" + 5
print(result)
except TypeError:
print("Invalid data types")
Output:
Invalid data types
Handling IndexError
numbers = [10, 20, 30]
try:
print(numbers[5])
except IndexError:
print("Invalid index")
Output:
Invalid index
Handling KeyError
student = {
"name": "Rahul",
"course": "Python"
}
try:
print(student["fees"])
except KeyError:
print("Key not found")
Output:
Key not found
Handling FileNotFoundError
try:
with open(
"students.txt",
"r"
) as file:
data = file.read()
print(data)
except FileNotFoundError:
print("File not found")
This is useful when the file may not exist.
Using as with except
We can store the exception object in a variable
using the as keyword.
try:
number = int("abc")
except ValueError as error:
print("Error:", error)
The variable error contains information
about the exception.
try & except with User Input
User input may contain invalid data, so exception handling is useful in input programs.
try:
marks = int(
input("Enter marks: ")
)
print("Marks:", marks)
except ValueError:
print("Please enter numbers only")
If the user enters text instead of a number,
the except block handles the problem.
When No Exception Occurs
If the code inside try does not
raise an exception, the except
block is skipped.
try:
number = 10 / 2
print(number)
except ZeroDivisionError:
print("Cannot divide by zero")
print("Program continues")
Output:
5.0
Program continues
Step-by-Step Execution
Step 1:
Python enters the try block.
↓
Step 2: Python executes the statements.
↓
Step 3:
If no exception occurs, Python skips
except.
↓
Step 4:
If an exception occurs, Python looks for
the matching except.
↓
Step 5: The exception handler executes.
Why Catch Specific Exceptions?
Catching a specific exception makes the program easier to understand and helps avoid hiding unrelated programming errors.
Less Specific
try:
number = int("abc")
except:
print("Something went wrong")
More Specific
try:
number = int("abc")
except ValueError:
print("Invalid number")
The second example clearly tells us which problem is being handled.
Using the General Exception Class
We can use Exception to catch many
standard exceptions.
try:
result = 10 / 0
except Exception as error:
print("Error:", error)
Use broad exception handling carefully so that important programming errors are not hidden.
Nested try Blocks
A try block can also be placed inside
another try block when the program
specifically requires nested error handling.
try:
number = int(
input("Enter a number: ")
)
try:
result = 100 / number
print(result)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid number")
Example: Student Marks 👀📩
try:
marks = int(
input("Enter student marks: ")
)
if marks < 0 or marks > 100:
print("Marks must be between 0 and 100")
else:
print("Valid marks:", marks)
except ValueError:
print("Please enter a valid number")
This example combines input validation with exception handling.
Best Practices
Specific Exceptions
Catch the expected exception type whenever practical.
Clear Messages
Provide useful information about the problem.
Small try Blocks
Keep the try block focused on operations that may fail.
Common Mistakes
-
Forgetting the
exceptblock. - Catching the wrong exception type.
-
Using a completely generic
exceptwithout understanding the error. -
Putting too much code inside the
tryblock. - Hiding useful error information.
Practice Programs
-
Handle division by zero using
ZeroDivisionError. -
Convert user input into an integer and handle
ValueError. - Handle an invalid list index.
- Handle a missing dictionary key.
- Handle a missing text file.
-
Print the exception message using
as error.
Summary
The try block contains code that may
raise an exception, while the except
block handles the exception. Python allows us to
catch specific exceptions such as
ValueError, TypeError,
IndexError, KeyError and
FileNotFoundError. Specific exception
handling makes programs easier to understand,
maintain and debug.