是否可以在不扩展 Exception 类的情况下在 Java 中创建自定义异常?
java 8object oriented programmingprogramming
异常是指程序执行过程中发生的问题(运行时错误)。发生异常时,程序会突然终止,并且生成异常的代码行之后的代码将永远不会执行。
用户定义异常
您可以在 Java 中创建自己的异常,这些异常称为用户定义异常或自定义异常。
- 所有异常都必须是 Throwable 的子类。
- 如果您想编写由 Handle 或 Declare 规则自动执行的已检查异常,则需要扩展 Exception 类。
- 如果您想编写运行时异常,则需要扩展 RuntimeException 类。
是否必须扩展 Exception 类?
不,创建自定义异常时无需扩展异常类,您可以通过扩展 Throwable 类(所有异常的超类)来创建它们。异常。
示例
以下 Java 示例创建了一个名为 AgeDoesnotMatchException 的自定义异常,该异常将用户年龄限制在 17 至 24 岁之间。这里我们创建它时并未扩展 Exception 类。
import java.util.Scanner; class AgeDoesnotMatchException extends Throwable{ AgeDoesnotMatchException(String msg){ super(msg); } } public class CustomException{ private String name; private int age; public CustomException(String name, int age){ try { if (age<17||age>24) { String msg = "Age is not between 17 and 24"; AgeDoesnotMatchException ex = new AgeDoesnotMatchException(msg); throw ex; } }catch(AgeDoesnotMatchException e) { e.printStackTrace(); } 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 Student: "); String name = sc.next(); System.out.println("Enter the age of the Student, should be 17 to 24 (including 17 and 24): "); int age = sc.nextInt(); CustomException obj = new CustomException(name, age); obj.display(); } }
输出
Enter the name of the Student: Krishna Enter the age of the Student, should be 17 to 24 (including 17 and 24): 30 july_set3.AgeDoesnotMatchException: Age is not between 17 and 24 Name of the Student: Krishna Age of the Student: 30 at july_set3.CustomException.<init>(CustomException.java:17) at july_set3.CustomException.main(CustomException.java:36)