javaloopstry-catchinfinitetry-catch-finally

Try/catch block in an infinity loop to print out something, if there is an infinity loop


this is my code (which is an infinity while loop. I should implement a try/catch block here, so that it stops, because it's going to infinity. My professor says we should implement a 'OutOfMemoryError', but I'm not sure how. It still goes to infinity in my case and ignores my try/catch block.

public class Infinite {

    public static void main(String[] args) {

        int[] myArray = { 2, 6, 8, 1, 9, 0, 10, 23, 7, 5, 3 };
 
            int length = myArray.length;
            int i = length;
            while (i < length + 6) {
                i--;
                System.out.println("hi");
            }
            System.out.println(" There is an error, it keeps on giving hi; ");
            System.exit(0);

        System.exit(0);
    }
}

This is what i did: (with this i still get an infinity loop.

public class Infinite {

    public static void main(String[] args) {

        int[] myArray = { 2, 6, 8, 1, 9, 0, 10, 23, 7, 5, 3 };
        
        try {
            int length = myArray.length;
            int i = length;
            while (i < length + 6) {
                i--;
                System.out.println("hi");
            }
        
        } finally {
            System.out.println(" There is an error, it keeps on giving hi; ");
        }
        System.exit(0);
    }
}

Solution

  • This error is thrown when the Java VM cannot allocate an object because it´s out of memory. No more memory could be made by the garabage collector. -> Trying to process to much data or eighter holding an object too long. This code throws this error:

    import java.util.*;
    
    public class Heap {
    
        public static void main(String args[]) {
            Integer[] array = new Integer[10000000 * 1000000];
        }
    }
    

    Error:

    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at Heap.main(Heap.java:8)
    

    Read more here: https://www.geeksforgeeks.org/understanding-outofmemoryerror-exception-java/