-1

The first one:

for (i = 0; i < 100; i++)
{
   try { n = s.pop(); }
   catch (EmptyStackException e) { . . . }
   try { out.writeInt(n); }
   catch (IOException e) { . . . }
}

The second one:

try
{
   for (i = 0; i < 100; i++)
   {
      n = s.pop();
      out.writeInt(n);
   }
}
catch (IOException e) { . . . }
catch (EmptyStackException e) { . . . }

I know that usually we use the second type of handling but I am trying to understand why it's better.

  • 3
    In the first example if you get the exception loop won't stop. In the second example loop will stop. – vszholobov Jul 25 '21 at 07:54
  • could you elaborate please? why is that? –  Jul 25 '21 at 07:59
  • Because in the thirst example catch block is inside the loop. In the second example it isn't. – vszholobov Jul 25 '21 at 08:01
  • You mean for the first one, if the code that was in the handling block were `System.out.println("hello")` it would be printed as many times as the exception is caught in the loop wheras for the second type, it will be printed only once. Am I right? –  Jul 25 '21 at 08:06
  • Yes, you are right. You can test it yourself, throwing Exception manually. – vszholobov Jul 25 '21 at 08:08
  • [Should try…catch go inside or outside a loop?](https://stackoverflow.com/q/141560) – Pshemo Jul 25 '21 at 08:43

3 Answers3

1

In the first example the loop will run through all turns with possible multiple exceptions, if you do not throw another exception within the catch block. Otherwise you will quit the loop for the first exception.

The second example will quit the loop for the first exception.

Michael Katt
  • 615
  • 1
  • 5
  • 18
0

As said in the comment section first example will run all iterations, even if exception occur. Second example will stop after thirst exception occur.

Also the first example can be attributed to fail-safe, and the second to fail-fast. You do not always prefer one to the other, you need to look at the situation.
Fail fast
Fail safe

vszholobov
  • 2,133
  • 1
  • 8
  • 23
0

There is absolutely no performance difference in where the try/catch structures are placed. Internally, they are implemented as a code-range table in a structure that is created when the method is called. While the method is executing, the try/catch structures are completely out of the picture unless a throw occurs, then the location of the error is compared against the table.

Well, actually there is no performance difference only if the code runs without exceptions.

And the differences mentioned in the other answers, well, not always true. It totally depends on the implementation, specifically what you are going to do in the catch block. If you do some task or do nothing in the catch block and then rethrow the exception, the loop will definitely break in this case.

devReddit
  • 2,696
  • 1
  • 5
  • 20