Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple try codes in one block

I have a problem with my code in the try block. To make it easy this is my code:

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 

Is something like this possible?

like image 949
arvidurs Avatar asked Jun 26 '13 14:06

arvidurs


People also ask

Can we write multiple try catch block?

You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally.

Can I have multiple try block in Python?

You cannot have that. A try block is not there to suppress exceptions across all code executed. It'll let you catch the exception when it happens, but the rest of the block is never executed.

How can we have more than catch for a single try block?

Yes you can have multiple catch blocks with try statement. You start with catching specific exceptions and then in the last block you may catch base Exception . Only one of the catch block will handle your exception. You can have try block without a catch block.

How many try catch blocks can be there?

Yes, we can define one try block with multiple catch blocks in Java.


1 Answers

You'll have to make this 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 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:

try:     code a except ExplicitException:     pass  try:     code b except ExplicitException:     pass  try:     code c except ExplicitException:     pass  try:     code d except ExplicitException:     pass 

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.

like image 104
Martijn Pieters Avatar answered Sep 19 '22 22:09

Martijn Pieters