如何修复 Java 中的"主线程中的异常"?
java 8object oriented programmingprogramming更新于 2025/4/26 19:07:17
异常是程序执行过程中发生的问题(运行时错误)。发生异常时,程序会突然终止,并且生成异常的行之后的代码永远不会执行。
示例
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 的不当使用。运行时异常在编译时被忽略。
主线程中的异常
运行时异常/未检查异常的显示模式为"主线程中的异常",即每当发生运行时异常时,消息都以此行开头。
示例
在下面的 Java 程序中,我们有一个大小为 5 的数组,我们试图访问第 6 个元素,这会生成 ArrayIndexOutOfBoundsException。
public class ExceptionExample { public static void main(String[] args) { //创建大小为 5 的整数数组 int inpuArray[] = new int[5]; //填充数组 inpuArray[0] = 41; inpuArray[1] = 98; inpuArray[2] = 43; inpuArray[3] = 26; inpuArray[4] = 79; //访问大于数组大小的索引 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) { //创建大小为 5 的整数数组 int inpuArray[] = new int[5]; //填充数组 inpuArray[0] = 41; inpuArray[1] = 98; inpuArray[2] = 43; inpuArray[3] = 26; inpuArray[4] = 79; //访问大于数组大小的索引 System.out.println( inpuArray[3]); } }
输出
26