How to continue execution of a java program after an Exception exception?

My sample code is as follows:

public class ExceptionsDemo { public static void main(String[] args) { try { int arr[]={1,2,3,4,5,6,7,8,9,10}; for(int i=arr.length;i<10;i++){ if(i%2==0){ System.out.println("i =" + i); throw new Exception(); } } } catch (Exception e) { System.err.println("An exception was thrown"); } } } 

My requirement is that after the exception is caught, I want to handle the remaining elements of the array. How can i do this?

+4
source share
5 answers

Your code should look like this:

 public class ExceptionsDemo { public static void main(String[] args) { for (int i=args.length;i<10;i++){ try { if(i%2==0){ System.out.println("i =" + i); throw new Exception(); // stuff that might throw } } catch (Exception e) { System.err.println("An exception was thrown"); } } } } 
+1
source

Move the catch try block to the for loop and then it should work

+6
source

You need to restructure it a bit so that try / catch is inside the for loop and not close it, for example.

 for (...) { try { // stuff that might throw } catch (...) { // handle exception } } 

As an aside, you should avoid using exceptions to control flow, for example: exceptions should be used for exceptional things.

+3
source

Just don't throw an exception and then:

 int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int i = 0; i < arr.length; i++) { if (i % 2 == 0) { System.out.println("i = " + i); } } 

Or throw it away and catch it inside the loop, not outside (but I see no reason to throw an exception in this trivial example):

 int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int i = 0; i < arr.length; i++) { try { if (i % 2 == 0) { System.out.println("i = " + i); throw new Exception(); } } catch (Exception e) { System.err.println("An exception was thrown"); } } 

Side note: See how code is much easier to read when it is indented correctly and contains spaces around statements.

+2
source

You cannot do this because your array is defined in a try clause. If you want to have access to it, move it from there. Also, perhaps you should somehow keep that I raised an exception in Exception so that you can continue with it.

+1
source

Source: https://habr.com/ru/post/1397036/


All Articles