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.

Community
  • 1
  • 1
Smit
  • 4,685
  • 1
  • 24
  • 28

4 Answers4

5

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

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

Dan D.
  • 32,246
  • 5
  • 63
  • 79
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.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
  • 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()); – Smit Sep 28 '12 at 17:49
  • :--->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. – Smit Sep 28 '12 at 18:29
1

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

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
1

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

ngoa
  • 720
  • 4
  • 14