【问题标题】:Unhandled exception type Java InstantiationException未处理的异常类型 Java InstantiationException
【发布时间】:2020-03-19 15:29:24
【问题描述】:

我正在尝试向我的代码添加异常,以便在 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 时发生异常?

【问题讨论】:

  • 异常不会总是触发。只是调用它的方法必须始终有一个“计划”当它发生时要做什么。他们必须要么捕获它声明他们自己捕获它。
  • 您不应为此使用 InstantiationException。这不是它的预期用途。 IllegalArgumentException 专为此目的而设计。

标签: java exception throw


【解决方案1】:

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

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

如果你想在运行时引发异常,你可以使用ErrorRuntimeException的子类型的unchecked Exception。 IDE 永远不会要求处理这些异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 2012-12-22
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多