Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have nested try-catch blocks in C++?

Tags:

Can I have nested try-catch blocks? For example:

 void f() {     try     {         //Some code          try         {              //Some code          }         catch(ExceptionA a)         {             //Some specific exception handling         }         //Some code     }     catch(...)     {         //Some exception handling     } }//f 
like image 579
Gal Goldman Avatar asked Feb 16 '09 14:02

Gal Goldman


People also ask

Can you have nested try-catch blocks?

Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.

Is nested try-catch OK?

No need for nested or multiple try-catches inside the same method. Code like the one you showed does indeed not make any sense in most if not all cases.

Can you nest a try block inside another try block in C++?

If the exception thrown from func2() in the inner try block is type_err , the program skips out of both try blocks to the second catch block without invoking func3() , because no appropriate catch block exists following the inner try block. You can also nest a try block within a catch block.

Can we have nested try-catch block in C#?

In C#, the nesting of the try & catch block is allowed. The nesting of try block means one try block can be nested into another try block.


1 Answers

Yes perfectly legal.

Though it would be best to move inner ones into another method so it looks cleaner and your method(s) are smaller

like image 87
ouster Avatar answered Sep 20 '22 04:09

ouster