首页 文章资讯内容详情

在java中如何修复处理线程main中的异常?

2026-06-04 1 花语

例外是程序执行期间发生的问题(运行时错误)。当发生异常时,程序会突然终止,并且生成异常的行之后的代码将永远不会执行。

示例

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) { //Creating an integer array with size 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