Java 中的 Exception 实例是已检查异常还是未检查异常?
异常是在程序执行期间发生的错误(运行时错误)。当发生异常时,程序会突然终止,异常行之后的代码将不会执行。
Java中有两种类型的异常。
- 未检查异常 - 未检查异常是在执行时发生的异常。这些也称为运行时异常。这些包括编程错误,例如逻辑错误或API的不正确使用。运行时异常在编译时会被忽略。
- 已检查异常 - 已检查异常是在编译时发生的异常,这些也称为编译时异常。这些异常在编译时不能被简单地忽略;程序员应该处理这些异常。
异常层次结构
在Java中,所有异常都是java.lang.Throwable类的子类。

Throwable和Exception类的所有实例都是已检查异常,RuntimeException类的实例是运行时异常。
例如,如果您通过扩展Exception类来创建一个用户定义的异常,则会在编译时抛出此异常。
示例
import java.util.Scanner;
class NotProperNameException extends Exception {
NotProperNameException(String msg){
super(msg);
}
}
public class CustomCheckedException{
private String name;
private int age;
public static boolean containsAlphabet(String name) {
for (int i = 0; i < name.length(); i++) {
char ch = name.charAt(i);
if (!(ch >= 'a' && ch <= 'z')) {
return false;
}
}
return true;
}
public CustomCheckedException(String name, int age){
if(!containsAlphabet(name)&&name!=null) {
String msg = "Improper name (Should contain only characters between a to z (all small))";
NotProperNameException exName = new NotProperNameException(msg);
throw exName;
}
this.name = name;
this.age = age;
}
public void display(){
System.out.println("Name of the Student: "+this.name );
System.out.println("Age of the Student: "+this.age );
}
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter the name of the person: ");
String name = sc.next();
System.out.println("Enter the age of the person: ");
int age = sc.nextInt();
CustomCheckedException obj = new CustomCheckedException(name, age);
obj.display();
}
}编译时异常
编译时,上述程序会生成以下异常。
CustomCheckedException.java:24: error: unreported exception NotProperNameException; must be caught or declared to be thrown throw exName; ^ 1 error
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP