簡體   English   中英

如果存在無限循環,則在無限循環中嘗試/捕獲塊以打印出某些內容

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

這是我的代碼(這是一個無限循環。我應該在這里實現一個 try/catch 塊,以便它停止,因為它會無限大。我的教授說我們應該實現一個“OutOfMemoryError”,但我不確定怎么樣。在我的例子中它仍然會無限大並且忽略我的 try/catch 塊。

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

這就是我所做的:(有了這個我仍然得到一個無限循環。

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

當 Java VM 無法分配 object 時會引發此錯誤,因為它超出了 memory。垃圾收集器無法再生成 memory。 -> 試圖處理太多數據或八個數據持有 object 時間太長。 此代碼拋出此錯誤:

import java.util.*;

public class Heap {

    public static void main(String args[]) {
        Integer[] array = new Integer[10000000 * 1000000];
    }
}

錯誤:

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

在此處閱讀更多信息: https://www.geeksforgeeks.org/understanding-outofmemoryerror-exception-java/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM