Nested try...except statements in Python
try...except
The _statement is used in Python to catch exceptions or run some error-prone code. Nowadays, every programming language has this feature, but in Python, it try...except
is represented by these words and _keywords respectively. Besides try...except
, another keyword, namely, finally
_, can also be used with them.
Like for
loops, these try
, , catch
and finally
statements can also be nested, and in this article, we will discuss that.
try...except
Nested statements
in Python
As mentioned above, we can for
nest these statements just like nested loops. See the following code for an example.
a = {"a": 5, "b": 25, "c": 125}
try:
print(a["d"])
except KeyError:
try:
print("a:", a["a"])
except:
print("No value exists for keys 'a' and 'd'")
finally:
print("Nested finally")
finally:
print("Finally")
Output:
a: 5
Nested finally
Finally
As we can see, the above program first initializes a dictionary with some key-value pairs and then tries to access d
the value for the key . Since no key-value pair exists, KeyError
an exception is raised and except
caught by the statement. The interpreter then try
runs the code under the nested block. Since a value exists for the key , it prints to the console and the code under the a
nested statement is executed . Finally, the code under the outer statement is executed.finally
finally
This means that we can put try
, , catch
and finally
statements under any try
, , catch
and finally
statements. Let's understand this with an example. We will write some code that contains try
, , catch
and statements, all of which also have , , and statements below them.finally
try
catch
finally
a = {
"a": 5,
"b": 25,
"c": 125,
"e": 625,
"f": 3125,
}
try:
try:
print("d:", a["d"])
except:
print("a:", a["a"])
finally:
print("First nested finally")
except KeyError:
try:
print("b:", a["b"])
except:
print("No value exists for keys 'b' and 'd'")
finally:
print("Second nested finally")
finally:
try:
print("c:", a["c"])
except:
print("No value exists for key 'c'")
finally:
print("Third nested finally")
Output:
a: 5
First nested finally
c: 125
Third nested finally
As we can see, first, the outer try
block is executed. Since no value is found for the key , the code under the d
nested statement will be executed and the nested will be executed. Since the outer block does not encounter any exception during execution, its block is skipped and the code under the outer block is executed.except
finally
try
except
finally
We can even go a step further and create n
nested try
, , catch
and finally
statements to the desired level. But as the number of nesting levels increases, the control flow or execution flow becomes a bit complex and difficult to manage. Navigating the try
, , catch
and finally
statements becomes challenging.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Convert a list to a set in Python
Publish Date:2025/05/08 Views:144 Category:Python
-
This tutorial demonstrates how to convert a list to a set in Python. Difference between List and Set Lists and sets are standard Python data types that store values in sequence. Python list stores comma separated values between
Remove the first element from a list in Python
Publish Date:2025/05/08 Views:172 Category:Python
-
This tutorial will discuss different ways on how to remove the first element from a list. pop() Remove the first element from a list using the pop() Method can remove an element from a specific index. We have to specify the index from which
Convert a list to lowercase in Python
Publish Date:2025/05/08 Views:112 Category:Python
-
Lists can be used to store multiple items in a single variable. In Python, we can create a list of strings by enclosing the different elements in the list in single or double quotes. This tutorial demonstrates how to convert a list of strin
Remove all occurrences of an element from a Python list
Publish Date:2025/05/08 Views:69 Category:Python
-
In Python, lists allow the same element to appear multiple times. Even though the value of an element may be the same as other elements, each element will have a different index. Using these index numbers, you can easily access any element
Convert hex to bytes in Python
Publish Date:2025/05/08 Views:101 Category:Python
-
Hexadecimal, often abbreviated to hex, uses 16 symbols (0-9, a-f) to represent values, in contrast to the decimal system's 10. For example, 1000 in decimal is 3E8 in hexadecimal. Being proficient in dealing with hexadecimal is essential for
b in front of string in Python
Publish Date:2025/05/08 Views:53 Category:Python
-
This tutorial will discuss the statement in Python b" . b" Using the statement in Python b" The notation is used to specify strings in Python bytes . In contrast to regular strings with ASCII characters, bytes a string is an array of byte v
How to Convert Integer to Binary in Python
Publish Date:2025/05/08 Views:130 Category:Python
-
This tutorial explains how to convert an integer to binary in Python. This tutorial also lists some sample codes to illustrate different ways of converting from int to binary in Python. bin() Convert Int to Binary in Python using In Python,
How to convert an integer to bytes
Publish Date:2025/05/08 Views:77 Category:Python
-
Converting an integer int to a byte bytes is the inverse of bytes converting a byte to an integer . Most of the to methods int described in this article are the inverse of the to methods. int bytes bytes int Generic method for converting in
How to convert bytes to int in Python
Publish Date:2025/05/08 Views:111 Category:Python
-
Bytes The data type has a numerical range of 0~255 (0x00~0xFF). A byte has 8 bits of data, that's why its maximum value is 0xFF. In some cases, you need to convert a byte or byte array to an integer for further data processing. Let's see ho