Java 中的异常实例是已检查异常还是未检查异常?

java 8object oriented programmingprogramming更新于 2025/9/22 14:36:17

异常是在程序执行过程中发生的问题(运行时错误)。发生异常时,程序会突然终止,并且生成异常的行之后的代码永远不会执行。

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

相关文章