Should try...catch go inside or outside a loop in Java
In this blog, we are going to know about the try…catch should go inside or outside a loop in Java.
The placement of the try/catch structures has no impact on performance whatsoever. When the method is invoked, a structure is constructed that contains them as a code-range table. Unless a throw happens, during which time the error’s location is checked against the table, the try/catch structures are entirely ignored while the method is running.
There is still a significant difference in usefulness even though performance may be the same and what “looks” better is very subjective. Consider the subsequent instance:
Integer j = 0;
try {
while (true) {
++j;
if (j == 20) { throw new Exception(); }
if (j%4 == 0) { System.out.println(j); }
if (j == 40) { break; }
}
} catch (Exception e) {
System.out.println("in catch block");
}
The variable “j” is increased until it reaches 40 in the while loop, printed out when j mod 4 is zero, and an exception is thrown when j reaches 20. The while loop is included within the try catch block.
Here’s another sample before getting into the intricacies
Integer i = 0;
while (true) {
try {
++i;
if (i == 20) { throw new Exception(); }
if (i%4 == 0) { System.out.println(i); }
if (i == 40) { break; }
} catch (Exception e) { System.out.println("in catch block"); }
}
The only difference from the previous reasoning is that the while loop now contains the try/catch section.
The output is seen below (while in try/catch):
4
8
12
16
in catch block
Moreover, the second output (try/catch in while)
4
8
12
16
in catch block
24
28
32
36
40
You can see a huge difference there: Breaks the loop while in try/catch, Keeps the loop active with try/catch in while.