首页 > 解决方案 > 未处理的异常类型 Java InstantiationException

问题描述

我正在尝试向我的代码添加一个异常,以便每当 securityManager 返回 false 时都会引发异常:

public Appointment(String date,String time) {
    //Secure Object Construction
    if (securityManager(date, time)) {
        this.date=date;
        this.time=time;
        System.out.println("Valid");
    }
    //Invalid Object, Throw Error
    else {
        throw new InstantiationException("Date provided is Invalid");
    }
    return;

但是,当我添加这个时,我有一个语法错误:

Unhandled exception type InstantiationException

IDE 想要添加以下行:

public Appointment(String date,String time) throws InstantiationException

但是,当我这样做时,总是会触发异常。

如何重新格式化代码,以便仅在 securityManager 返回 false 时发生异常?

标签: javaexceptionthrow

解决方案


InstantiationException是一个检查异常。你必须处理它,否则编译器会报这个异常。

已检查异常的示例有ClassNotFoundExceptionIOExceptionSQLException等。

如果你想在运行时引发异常,你可以使用未检查的异常,它是Error和的子类型RuntimeException。IDE 永远不会要求处理这些异常。


推荐阅读