這是我的代碼(這是一個無限回圈。我應該在這里實作一個 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);
}
}
uj5u.com熱心網友回復:
當 Java VM 由于記憶體不足而無法分配物件時會拋出此錯誤。垃圾收集器無法產生更多的記憶體。-> 試圖處理太多資料或持有一個物件太久。此代碼拋出此錯誤:
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/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/537543.html
