如何在 Java 中修復“Exception in thread main”?
異常是在程式執行期間發生的錯誤(執行時錯誤)。當發生異常時,程式會突然終止,並且異常行之後的程式碼永遠不會執行。
示例
import java.util.Scanner;
public class ExceptionExample {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number: ");
int a = sc.nextInt();
System.out.println("Enter second number: ");
int b = sc.nextInt();
int c = a/b;
System.out.println("The result is: "+c);
}
}輸出
Enter first number: 100 Enter second number: 0 Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionExample
異常型別
在 Java 中,有兩種型別的異常
- 檢查異常 − 檢查異常是在編譯時發生的異常,也稱為編譯時異常。在編譯時不能簡單地忽略這些異常;程式設計師應該注意(處理)這些異常。
- 未檢查異常 − 未檢查異常是在執行時發生的異常。這些也稱為執行時異常。這些包括程式設計錯誤,例如邏輯錯誤或 API 的不正確使用。執行時異常在編譯時會被忽略。
Exception in thread main
執行時異常/未檢查異常的顯示模式為“Exception in thread main”,即每當發生執行時異常時,訊息都會以該行開頭。
示例
在下面的 Java 程式中,我們有一個大小為 5 的陣列,我們試圖訪問第 6 個元素,這會生成 ArrayIndexOutOfBoundsException。
public class ExceptionExample {
public static void main(String[] args) {
//Creating an integer array with size 5
int inpuArray[] = new int[5];
//Populating the array
inpuArray[0] = 41;
inpuArray[1] = 98;
inpuArray[2] = 43;
inpuArray[3] = 26;
inpuArray[4] = 79;
//Accessing index greater than the size of the array
System.out.println( inpuArray[6]);
}
}執行時異常
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at MyPackage.ExceptionExample.main(ExceptionExample.java:14)
示例
在下面的示例中,我們嘗試使用負數作為大小值來建立陣列,這會生成 NegativeArraySizeException。
public class Test {
public static void main(String[] args) {
int[] intArray = new int[-5];
}
}執行時異常
執行此程式時,會生成如下所示的執行時異常。
Exception in thread "main" java.lang.NegativeArraySizeException at myPackage.Test.main(Test.java:6)
處理執行時異常
您可以處理執行時異常並避免異常終止,但是,Java 中沒有針對執行時異常的特定修復方法,具體取決於異常型別,您需要更改程式碼。
例如,如果您需要修復上面列出的第一個程式中的 ArrayIndexOutOfBoundsException,則需要刪除/更改訪問陣列索引位置超出其大小的行。
示例
public class ExceptionExample {
public static void main(String[] args) {
//Creating an integer array with size 5
int inpuArray[] = new int[5];
//Populating the array
inpuArray[0] = 41;
inpuArray[1] = 98;
inpuArray[2] = 43;
inpuArray[3] = 26;
inpuArray[4] = 79;
//Accessing index greater than the size of the array
System.out.println( inpuArray[3]);
}
}輸出
26
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP