Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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);
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading