I have a problem with my code in the try block. To make it easy this is my code:
JavaScript
x
8
1
try:
2
code a
3
code b #if b fails, it should ignore, and go to c.
4
code c #if c fails, go to d
5
code d
6
except:
7
pass
8
Is something like this possible?
Advertisement
Answer
You’ll have to make this separate try
blocks:
JavaScript
1
16
16
1
try:
2
code a
3
except ExplicitException:
4
pass
5
6
try:
7
code b
8
except ExplicitException:
9
try:
10
code c
11
except ExplicitException:
12
try:
13
code d
14
except ExplicitException:
15
pass
16
This assumes you want to run code c
only if code b
failed.
If you need to run code c
regardless, you need to put the try
blocks one after the other:
JavaScript
1
20
20
1
try:
2
code a
3
except ExplicitException:
4
pass
5
6
try:
7
code b
8
except ExplicitException:
9
pass
10
11
try:
12
code c
13
except ExplicitException:
14
pass
15
16
try:
17
code d
18
except ExplicitException:
19
pass
20
I’m using except ExplicitException
here because it is never a good practice to blindly ignore all exceptions. You’ll be ignoring MemoryError
, KeyboardInterrupt
and SystemExit
as well otherwise, which you normally do not want to ignore or intercept without some kind of re-raise or conscious reason for handling those.