Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Explain try, except and finally statements in Python.
In Python, the try, except, and finally blocks are used to handle exceptions. These blocks allow you to catch errors that occur during the execution of a program and respond accordingly, which helps to prevent your program from crashing.
Try and Except Blocks
The try block contains code that might raise an exception. If an exception occurs, the except block handles it, preventing the program from crashing.
Example: Handling ZeroDivisionError
In this example, we are dividing a number by zero, which raises an exception and is handled by the except block -
try:
result = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero.")
We get the following output -
You cannot divide by zero.
Finally with Try and Except
The finally block always executes, no matter whether an exception was raised or not in the try and except blocks. It is generally used for cleanup tasks.
Example with try, except, and finally
In this example, we are trying to open a file that does not exist. The except block handles the FileNotFoundError, and the finally block runs cleanup code irrespective of whether the error occurred or not -
try:
f = open("nonexistent.txt")
except FileNotFoundError:
print("File not found.")
finally:
print("Closing program.")
Following is the output obtained -
File not found. Closing program.
Using else with try and except
The else block runs only if no exceptions are raised in the try block. It is useful for code that should only run when everything succeeds.
Example: Else block execution
In this example, we are successfully converting a string to an integer, so the else block runs -
try:
num = int("100")
except ValueError:
print("Invalid input.")
else:
print("Conversion successful:", num)
The output obtained is as follows -
Conversion successful: 100
Multiple except blocks
Python allows multiple except blocks to handle different exception types individually. This helps catch and manage various errors separately.
Example
In the following example, we are handling two types of exceptions separately using multiple except blocks -
try:
number = int("hello")
except ValueError:
print("Invalid input. Cannot convert to integer.")
except TypeError:
print("Type error occurred.")
We get the following output -
Invalid input. Cannot convert to integer.
Finally without Except
The finally block can be used without an except. It will still run whether the try block throws an error or not.
Example
In the following example, we are using try and finally without an except block. The finally block still runs after the error -
try:
x = 1 / 0
finally:
print("This will always execute.")
We will get the following output -
This will always execute. Traceback (most recent call last): ... ZeroDivisionError: division by zero
Nested try-except blocks
You can nest try blocks inside one another. This helps you to catch errors at different levels of logic in complex applications.
Example: Inner and outer try blocks
In this example, we are dividing by zero inside an inner try block and handling it, while the outer block does nothing -
try:
try:
result = 10 / 0
except ZeroDivisionError:
print("Handled in inner try.")
except:
print("Handled in outer try.")
The output obtained is -
Handled in inner try.
Using raise inside except
You can re-raise exceptions using the raise statement inside the except block if you want it to continue being raised after it has been handled.
Example: Re-raising an exception
In this example, we are catching the error, printing a message, and then raising it again -
try:
try:
x = 10 / 0
except ZeroDivisionError:
print("Caught division error.")
raise
except:
print("Outer handler caught the re-raised exception.")
Following is the output obtained -
Caught division error. Outer handler caught the re-raised exception.