Java 中的用户定义和自定义异常

java 8object oriented programmingprogramming更新于 2025/11/7 7:08:17

异常是指程序执行过程中发生的问题(运行时错误)。为了便于理解,我们换个角度来理解。

通常,编译程序时,如果未编译,则会创建一个 .class 文件。.class 文件是 Java 中的可执行文件,每次执行此 .class 文件时,程序都应该能够成功运行,并且不会出现任何问题。但是,在某些异常情况下,JVM 在执行程序时会遇到一些模棱两可的情况,不知道该做什么。

以下是一些示例场景 −

  • 假设你有一个大小为 10 的数组,如果代码中的一行尝试访问该数组中的第 11 个元素。

  • 如果你尝试用 0 除以一个数(结果为无穷大,JVM 无法对其进行求值)。

这种情况称为异常,当发生异常时,程序会异常终止。某些异常在编译时触发,它们被称为已检查异常(或编译时异常);而运行时发生的异常被称为运行时异常(或非已检查异常)。

每种可能的异常都由一个预定义的类表示,所有这些类都可以在 java.lang 包中找到。以下是一些异常类

NullPointerException、ArrayIndexOutOfBoundsException、ClassCastException、IllegalArgumentException、IllegalStateException 等……

示例:ArithmeticException

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.main(ExceptionExample.java:10)

示例:ArrayIndexOutOfBoundsException

import java.util.Arrays;
import java.util.Scanner;
public class AIOBSample {
   public static void main(String args[]){
      int[] myArray = {1254, 1458, 5687,1457, 4554, 5445, 7524};
      System.out.println("Elements in the array are: ");
      System.out.println(Arrays.toString(myArray));
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the index of the required element: ");
      int element = sc.nextInt();
      System.out.println("Element in the given index is :: "+myArray[element]);
   }
}

输出

Run time exception −

Elements in the array are:
[897, 56, 78, 90, 12, 123, 75]
Enter the index of the required element:
7
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at AIOBSample.main(AIOBSample.java:12)

示例: ArrayStoreException

import java.util.Arrays;
public class ArrayStoreExceptionExample {
   public static void main(String args[]) {
      Number integerArray[] = new Integer[3];
      integerArray[0] = 12548;
      integerArray[1] = 36987;
      integerArray[2] = 555.50;
      integerArray[3] = 12548;
      System.out.println(Arrays.toString(integerArray));
   }
}

输出

Runtime Exception −

Exception in thread "main" java.lang.ArrayStoreException: java.lang.Double
at ther.ArrayStoreExceptionExample.main(ArrayStoreExceptionExample.java:9)

示例: NoSuchElementException

import java.util.Enumeration;
import java.util.Vector;
public class EnumExample {
   public static void main(String args[]) {
      //实例化一个 Vector
      Vector<Integer> vec = new Vector<Integer>();
      //填充 Vector
      vec.add(1254);
      vec.add(4587);
      //使用枚举检索元素
      Enumeration<Integer> en = vec.elements();
      System.out.println(en.nextElement());
      System.out.println(en.nextElement());
      //到达末尾后获取下一个元素
      System.out.println(en.nextElement());
   }
}

输出

Runtime Exception −

1254
4587
Exception in thread "main" java.util.NoSuchElementException: Vector Enumeration
at java.util.Vector$1.nextElement(Unknown Source)
at July_set2.EnumExample.main(EnumExample.java:18)

用户定义异常

您可以在 Java 中创建自己的异常,这些异常称为用户定义异常或自定义异常。

要创建用户定义异常,请扩展上述类之一。要显示消息,请重写 toString() 方法,或者调用超类的参数化构造函数,绕过字符串格式的消息。

MyException(String msg){
   super(msg);
}
Or,
public String toString(){
   return " MyException [Message of your exception]";
}

然后,在其他需要引发此异常的类中,创建自定义异常类的对象,并使用 throw 关键字抛出该异常。

MyException ex = new MyException ();
If(condition…hellip;…hellip;…hellip;.){
   throw ex;
}

自定义 Checked 和自定义 Unchecked

  • 所有异常都必须是 Throwable 的子类。

  • 如果要编写由 Handle 或 Declare 规则自动执行的 Checked 异常,则需要扩展 Exception 类。

  • 如果要编写运行时异常,则需要扩展 RuntimeException 类。

示例:自定义 Checked 异常

以下 Java 程序演示了如何创建自定义 Checked 异常。

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

示例:自定义 unChecked 异常

如果您只是将自定义异常继承的类更改为 RuntimeException,它将在运行时抛出。

class NotProperNameException extends RuntimeException {
   NotProperNameException(String msg){
      super(msg);
   }
}

如果您将 NotProperNameException 类替换为上述代码并运行上述程序,则会生成以下运行时异常。

输出

运行时异常

Enter the name of the person:
Krishna1234
Enter the age of the person:
20
Exception in thread "main" july_set3.NotProperNameException: Improper name (Should contain only characters between a to z (all small))
at july_set3.CustomCheckedException.<init>(CustomCheckedException.java:25)
at july_set3.CustomCheckedException.main(CustomCheckedException.java:41)

相关文章