. Advertisement .
..3..
. Advertisement .
..4..
In Python you may face some problems when you enter code but it fails. You do multiple try codes in one block but their result returns a failure. This issue ”the multiple try codes in one block” is bothering you and is finding ways to fix it? Let’s read this post to find the solution for it. It becomes easy to fix if you know the key that we will instruct here.
When will we encounter ”the multiple try codes in one block” problem?
Let’s look at this example. We are having a trouble with our codes in the try block.
try:
code a
code b #if b fails, it should ignore, and go to c.
code c #if c fails, go to d
code d
except:
pass
From above program, you can see that we put all try codes (code a, code b, code c, code d) in one block, so the program does not work. When code b fails, it gives a request to reach the code c and when code c fails, it requires continously going to code d.
How to solve ”multiple try codes in one block” problem
To solve this issue, we have to put the try codes in distinct block by creating separate try blocks.
try:
code a
except ExplicitException:
pass
try:
code b
except ExplicitException:
try:
code c
except ExplicitException:
try:
code d
except ExplicitException:
pass
This supposes that we only want to execute code C only when code b failes.
Put the try blocks one after the other as the following if we must execute function c anyway:
try:
code a
except ExplicitException:
pass
try:
code b
except ExplicitException:
pass
try:
code c
except ExplicitException:
pass
try:
code d
except ExplicitException:
pass
It is never a good method to blithely ignore all exceptions, so we are utilizing the except ExplicitException here. If we don’t handle MemoryError, KeyboardInterrupt, and SystemExit, and something we typically don’t want to do without a re-raise or other deliberate cause, we’ll also ignore them.
Conclusion
We hope our simple suggestion for multiple try codes in one block was beneficial to you. Just try our solution to get the right result and share this experience with your friend to practice if both of you have the same lesson. Practicing veryver is the best way to remove the trouble problem and explore the new lesson for the program language. Please let us know your ideas and questions in the comment box if you want to know more about this problem.
Leave a comment