- Learning Objectives
- Prerequisites
- Introduction
- What is a try Block?
- What is an except Block?
- Why are try-except Blocks Required?
- Syntax
- Flow of Execution
- Multiple except Blocks
- Nested try-except Blocks
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Understand the try block.
- Understand the except block.
- Learn how Python handles exceptions.
- Use multiple except blocks.
- Implement nested try-except blocks.
- Write robust Python programs.
Before learning this chapter, you should know:
- Exception Handling
- Runtime Errors
- Variables
- Functions
- Control Statements
In the previous chapter,
we learned that runtime errors interrupt the normal execution of a program.
Consider the following example.
number = 10
result = number / 0
print(result)
print("Program Completed")Output
ZeroDivisionError:
division by zero
The last statement
print("Program Completed")never executes.
To prevent this,
Python provides the
try-exceptmechanism.
It allows the program to handle exceptions gracefully and continue execution.
A try block contains code that may generate an exception.
Python continuously monitors the statements inside the try block.
If an exception occurs,
Python immediately stops executing the remaining statements inside the try block and searches for a matching except block.
The try block contains code that may produce an exception.
An except block contains the code that handles an exception.
If a matching exception occurs inside the try block,
Python transfers control to the corresponding except block.
The except block handles exceptions raised inside the try block.
Suppose we are developing a Login System.
A user enters incorrect input.
Without Exception Handling,
the application may terminate.
With try-except,
the application can display a meaningful message such as
Invalid Input
Please Try Again
and continue execution.
try-except blocks are commonly used in:
- Banking Applications
- ATM Machines
- Login Systems
- File Handling
- Database Connections
- Network Communication
- Payment Gateways
- Web Applications
try:
# Risky Code
except:
# Exception Handling Codetry:
# Risky Code
except ZeroDivisionError:
# Handle Division by Zerotry:
# Risky Code
except ValueError:
# Handle ValueError
except TypeError:
# Handle TypeErrorPython executes the try-except block in the following order.
Program Starts
↓
Enter try Block
↓
Execute Statement
↓
Exception Occurs?
↓
No
↓
Skip except Block
↓
Continue Program
----------------------
Yes
↓
Search Matching except
↓
Found?
↓
Yes
↓
Execute except Block
↓
Continue Program
----------------------
No
↓
Program Terminates
A try block can have multiple except blocks.
Each except block handles a specific type of exception.
Example
try:
# Risky Code
except ZeroDivisionError:
pass
except ValueError:
pass
except TypeError:
passPython executes only the first matching except block.
A try block may contain another try-except block.
Example
try:
try:
# Risky Code
except ValueError:
pass
except ZeroDivisionError:
passNested try-except blocks are useful when different parts of a program require independent exception handling.
Enter try Block
↓
Execute Statements
↓
Exception Raised?
↓
No
↓
Skip except Block
↓
Continue Program
--------------------
Yes
↓
Create Exception Object
↓
Search Matching except
↓
Execute Handler
↓
Continue Program
- Prevents abnormal program termination.
- Makes applications more reliable.
- Improves user experience.
- Separates normal logic from error-handling logic.
- Makes debugging easier.
- Keep the try block as small as possible.
- Catch only expected exceptions.
- Display meaningful error messages.
- Use specific exception classes whenever possible.
- Avoid writing unnecessary code inside the try block.
Writing all program logic inside the try block.
Only risky statements should be placed inside try.
Using a generic except block unnecessarily.
Prefer
except ZeroDivisionError:instead of
except:whenever possible.
Ignoring exceptions completely.
Avoid empty exception handlers unless there is a valid reason.
A try block contains code that may generate an exception.
An except block handles exceptions raised inside the corresponding try block.
The except block is skipped and the program continues normally.
Yes.
Each except block can handle a different type of exception.
Yes.
Python allows nested try-except blocks.
- try → Risky Code
- except → Exception Handling
- Multiple except blocks are supported.
- Nested try-except blocks are allowed.
- Python executes only the first matching except block.
In this chapter, you learned:
- try Block
- except Block
- Flow of Execution
- Multiple except Blocks
- Nested try-except Blocks
- Internal Working
- Best Practices
- Common Mistakes
- Interview Questions
- Quick Revision
Write a Python program to handle a division by zero exception.
try:
number = 10
result = number / 0
print(result)
except ZeroDivisionError:
print("Cannot divide by zero.")
print("Program Completed")Cannot divide by zero.
Program Completed
When division by zero occurs,
Python raises a ZeroDivisionError.
The matching except block executes,
and the program continues normally.
try:
age = int(input("Enter Age : "))
print("Age :", age)
except ValueError:
print("Please enter a valid integer.")Enter Age : abc
Please enter a valid integer.
If the user enters non-numeric data,
int() raises a ValueError.
try:
number = int(input("Enter Number : "))
result = 100 / number
print(result)
except ZeroDivisionError:
print("Division by zero is not allowed.")
except ValueError:
print("Please enter a valid integer.")Enter Number : 0
Division by zero is not allowed.
Enter Number : abc
Please enter a valid integer.
Python executes only the first matching except block.
try:
number = 10 / 0
except ZeroDivisionError as error:
print("Exception :", error)Exception : division by zero
Using
as errorstores the exception object,
allowing us to display the actual error message.
try:
value = int("Python")
except Exception as error:
print("Error :", error)Error : invalid literal for int() with base 10: 'Python'
Exception is the base class for most user-handled exceptions.
It can handle different exception types.
try:
print("Outer try")
try:
print(10 / 0)
except ZeroDivisionError:
print("Inner Exception Handled")
except Exception:
print("Outer Exception Handled")Outer try
Inner Exception Handled
The inner try-except handles the exception.
Therefore,
the outer except block is not executed.
try:
file = open("student.txt")
except FileNotFoundError:
print("File does not exist.")File does not exist.
Attempting to open a non-existing file raises a FileNotFoundError.
try:
numbers = [10, 20, 30]
print(numbers[5])
except IndexError:
print("Invalid list index.")Invalid list index.
try:
student = {
"name": "Rahul"
}
print(student["age"])
except KeyError:
print("Key not found.")Key not found.
try:
number = 100 / 5
print(number)
except ZeroDivisionError:
print("Exception Occurred")
print("Program Completed")20.0
Program Completed
Since no exception occurs,
the except block is skipped.
Execution continues normally.
Enter try Block
↓
Execute Statement
↓
Exception Occurs?
↓
No
↓
Skip except
↓
Continue Execution
--------------------
Yes
↓
Matching except Found
↓
Execute except Block
↓
Continue Program
Program
↓
try Block
↓
Risky Statements
↓
Exception?
↓
No → Continue
↓
Yes
↓
Exception Object
↓
except Block
↓
Program Continues
- Prevents abnormal program termination.
- Improves application reliability.
- Separates error-handling logic from business logic.
- Makes debugging easier.
- Improves user experience.
- Keep the
tryblock as small as possible. - Catch specific exceptions whenever possible.
- Use
Exceptiononly when necessary. - Display meaningful error messages.
- Avoid empty
exceptblocks.
Using
except:for every exception.
Prefer
except ValueError:or another specific exception.
Writing too many statements inside the try block.
Only risky code should be placed inside it.
Ignoring exception details.
Use
except Exception as error:when you need to inspect the exception message.
Assuming execution returns to the failed statement.
After an exception is handled,
execution continues with the first statement after the entire try-except block.
A try block contains code that may raise an exception.
An except block handles exceptions raised inside the corresponding try block.
Yes.
Python executes only the first matching except block.
It stores the exception object so that its message can be accessed and displayed.
The except block is skipped, and program execution continues normally.
Yes.
Nested try-except blocks are supported in Python.
No.
Specific exception classes should be preferred whenever possible.
- Handle
ZeroDivisionError. - Handle
ValueErrorfrom user input. - Handle
IndexErrorin a list. - Handle
KeyErrorin a dictionary. - Demonstrate nested
try-except.
try→ Risky codeexcept→ Exception handler- Multiple
exceptblocks are supported. - Nested
try-exceptis allowed. Exception as eprovides the exception object.- Python executes only the first matching
exceptblock.
In this chapter, you learned:
- try Block
- except Block
- Multiple Exception Handling
- Nested try-except
- Exception Objects
- Practical Programs
- Best Practices
- Common Mistakes
- Interview Questions
- Practice Programs
- Quick Revision