如何在 java 中创建用户定义异常(自定义异常)?
java 8object oriented programmingprogramming
异常是程序执行过程中发生的问题(运行时错误)。发生异常时,程序会突然终止,并且生成异常的行之后的代码永远不会执行。
示例
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)
用户定义的异常
您可以在 Java 中创建自己的异常。
所有异常都必须是 Throwable 的子类。
如果您想编写由 Handle 或 Declare 规则自动执行的已检查异常,则需要扩展 Exception 类。
如果您想编写运行时异常,则需要扩展 RuntimeException 类。
要创建用户定义的异常,请扩展上述类之一。要显示消息,请重写 toString() 方法,或者通过传递字符串格式的消息来调用超类参数化构造函数。
AgeDoesnotMatchException(String msg){ super(msg); } 或者, public String toString(){ return "CustomException[Age is not between 17 and 24]"; }
然后,在需要引发此异常的其他类中,创建创建的自定义异常类的对象,并使用 throw 关键字抛出异常。
MyException ex = new MyException (); If(condition……….){ throw ex; }
示例
在下面的 Java 程序中,我们创建了一个名为 AgeDoesnotMatchException 的自定义异常类。
public class AgeDoesnotMatchException extends Exception{ (String msg){ super(msg); } }
另一个 Student 类包含两个私有变量 name、age 和一个初始化实例变量的参数化构造函数。
从主方法中,我们接受来自用户的 name 和 age 值,并通过传递接受的值来初始化 Student 类。
在 Student 类的构造函数中,我们创建了一个异常 AgeDoesnotMatchException 的对象,如果 age 值介于 17 和 24 之间,则引发异常(使用 throws)。
public class Student extends RuntimeException { private String name; private int age; public Student(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(); Student obj = new Student(name, age); obj.display(); } }
输出
执行此程序时,您需要从键盘传递姓名和年龄值。如果给定的年龄值不在 17 至 24 之间,则会发生异常,如下所示 −
Enter the name of the Student: Krishna Enter the age of the Student should be 17 to 24 (including 17 and 24): 14 AgeDoesnotMatchException: Age is not between 17 and 24 Name of the Student: Krishna' Age of the Student: 14 at Student.<init>(Student.java:18) at Student.main(Student.java:39)