如何在 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