【问题标题】:Throw exception in class declaration在类声明中抛出异常
【发布时间】:2013-03-28 14:22:38
【问题描述】:

我试图在类的声明中抛出异常。像这样的:

class myClass throws A_Dangerous_Exception implements Something_to_Implement {

...

}

有什么建议吗?

【问题讨论】:

    标签: java class exception throw


    【解决方案1】:

    你不能。异常只能从方法或构造函数中抛出。你可以这样做:

    class myClass implements Something_to_Implement {
    
       public myClass() throws A_Dangerous_Exception {
          ...
       }
    }
    

    在从构造函数抛出异常之前,请注意整理所有资源,例如FileOutputStream。

    阅读:Exceptions

    【讨论】:

      【解决方案2】:

      你不能那样做。您可能的意思是从类的构造函数中抛出异常:

      class myClass implements Something_to_Implement {
        myClass() throws A_Dangerous_Exception {}
      }
      

      如果你有多个构造函数,每个都可以有一个不同的throws 子句,如果你愿意的话:

      class myClass implements Something_to_Implement {
        myClass() throws A_Dangerous_Exception {}
        myClass(int a) throws A_Dangerous_Exception, A_Not_So_Dangerous_Exception {}
      }
      

      然后,无论何时实例化该类,都必须处理异常,方法是捕获它们或在实例化类的方法的 throws 子句中声明它们:

      void myMethod() {
        try {
          new myClass();
        } catch (A_Dangerous_Exception e) {}
      }
      

      或

      void myMethod() throws A_Dangerous_Exception {
        new myClass();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        • 1970-01-01
        • 2021-04-20
        • 1970-01-01
        • 2015-07-21
        • 1970-01-01
        相关资源
        最近更新 更多