1

I have very simple question. I am not using it but I have curiosity to know the answer. Can we execute multiple statements in catch block only if the exception get catched? I mean in my code below will both statement will get executed or not? Let me add some code snippet to make it clear..

I have found this link but not giving me the answer to my question. link Click Here

The above link I found in this question asked by someone but It has very blurry code so hard to understand. stackoverflow Link

try { int x = doXProcess(); int y = doYProcess(); } catch (Exception e) { System.out.println("Error related x: " x + e.printStackTrace()); System.out.println("Error related y: " y + e.printStackTrace()); } 

Thanks you for your help and time.

2
  • Use a debugger to see how it works ;-) Commented Sep 28, 2012 at 17:23
  • No I did not tried it. While working I came to this situation. I know how to handle it, but this one code is just curiosity. Commented Sep 28, 2012 at 17:27

4 Answers 4

5

You can definitely execute several lines in the block of code handling the exception.

However, please note that your code doesn't compile.

Sign up to request clarification or add additional context in comments.

Comments

3

It is common to see multiple statements in a try block.

If an exception occurs on the first line, the second line is not executed. Execution stops on any line where an exception is thrown; no lines past that point in the block are executed -- execution proceeds directly to the catch block.

If an exception is thrown from the catch block, execution again stops at the line on which the exception occurred. From there you go to a finally block, if one is defined.

2 Comments

So in this case when exception get cought the following statement get executed and then program will get stopped executing. Catch block won'e even bother to execute next statement. System.out.println("Error related x: " x + e.printStackTrace());
:--->Yes I got the answer. I have did the experiment on it and I found the answer, but currently stackoverflow is not letting me to post the answer. I will post it later. Thanks for your help.
1

Yes, all the statements in the catch block are executed when a exception is caught.

Comments

1

Yes you can. N number of statement can be executable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.