是否可以在Java中创建自定义异常而无需扩展Exception类?
例外是程序执行期间发生的问题(运行时错误)。当发生异常时,程序会突然终止,并且生成异常的行之后的代码将永远不会执行。
用户定义的例外
您可以使用Java创建自己的异常,这些异常称为用户定义的异常或自定义异常。
所有例外必须是Throwable的子级。
如果要编写由Handle或DelareRule自动执行的已检查异常,则需要扩展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)