【问题标题】:Throwing exceptions outside of a method - Java在方法之外抛出异常 - Java
【发布时间】:2015-11-28 03:06:16
【问题描述】:

我是 Java 初学者。

我将一个方法声明为public void method() throws Exception,但每当我尝试使用method(); 在同一类的另一个区域中调用该方法时,我都会收到错误消息:

Error: unreported exception java.lang.Exception; must be caught or declared to be thrown

如何使用该方法而不出现此错误?

【问题讨论】:

  • 当您调用该方法时,您需要用 try-catch 包围调用,或者重新抛出异常。
  • @azurefrog 对,我可以打电话给method() throws Exception;吗?

标签: java exception throw checked-exceptions


【解决方案1】:

在另一个调用method() 的方法中,您必须以某种方式处理method() 抛出的异常。在某些时候,它要么需要被捕获,要么一直声明到启动整个程序的main() 方法。所以,要么捕获异常:

try {
    method();
} catch (Exception e) {
    // Do what you want to do whenever method() fails
}

或在您的其他方法中声明它:

public void otherMethod() throws Exception {
    method();
}

【讨论】:

    【解决方案2】:

    throws 关键字用于声明异常。 而 throw 关键字用于显式抛出异常。 如果你想定义一个用户定义异常,那么 ....

    class exps extends Exception{
    exps(String s){
        super(s);
     }
    }
    
    class input{
     input(String s) throws exps {
         throw new exps(s);
     }
    
    }
    
    public class exp{
     public static void main(String[] args){
         try{
             new input("Wrong input");
         }catch(exps e){
            System.out.println(e.getMessage());
         }
      }
    }
    

    Java try 块用于封装可能引发异常的代码。必须在方法中使用。

    【讨论】:

      【解决方案3】:

      您需要用类似这样的 try-catch 块包围 method() 调用:

      try {
          method();
      } catch (Exception e) {
          //do whatever
      }
      

      或者您可以将throws 添加到调用method() 的方法中。
      示例:

      public void callingMethod() throws Exception {
          method();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-04
        • 1970-01-01
        • 1970-01-01
        • 2014-06-25
        • 2012-12-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多