try catch blocks scope

Hello.
If you put something inside try block, does it apply on everything inside try block? Like if you open new blocks or loops inside, does the try / catch apply to them also? Kind of silly question, but I’m debuging and I’m little bit confused about output to console. Thank you.

Scope is between { and }


{
   int a = 6;

   { // A is still accessible in here
       int b = 5;
   }  // B is not accessible anymore
} // A is not accessible anymore

so the try/catch code doesn’t really matter, only the { and }

When you have a try-catch block inside another, any exception thrown within the nested try will be caught by the nested try’s catch and not the outer try’s catch unless you re-throw it.

For example, the following will print “caught in nested try” only:

try{
try{
throw new Exception()
}
catch(Exception e){
System.out.println(“caught in nested try”);
}
}
catch(Exception e){
System.out.println(“caught in outer try”);
}

thank you guys… Allthough it wasn’t a direct anwser it can be figured out from it.

I was actually asking will something like this be cought:

try {
throw new Exception() // - this will be cougth
while (something) {
throw new Exception() // - wasnt sure about this since it’s in a new block
}
}

It’s clear now that both will be cought. Thanks.

Direct answers are bad

You will never reach the while as the first throw will jump you out to the catch block.

In fact, this shouldnt even compile as you have provably unreachable code…

You know, I have a feeling it was a contrived example to illustrate a point :wink:

Kev

Maybe, but even so he asked “what does this do.”

Thats the answer.