【问题标题】:Try Catching from another Method尝试从其他方法捕获
【发布时间】:2013-01-29 00:04:47
【问题描述】:

尝试从另一种方法中获取:

method1(){
   try {

       method2();

   }catch(Exception e){


   }
}

 method2(){
    try{

       //ERROR FROM HERE

    }catch(Exception e){

    }

 }

method1() 将如何捕获来自method2() 的错误?

【问题讨论】:

  • 不会因为method2() 已经捕捉到它。不过,您可以去掉 method2() 中的 try/catch 块并添加 throws 声明。这样,该方法将被传递给调用者。

标签: java exception try-catch


【解决方案1】:

method1() 不会捕获错误,除非您从 method2() 中的 catch 块重新抛出它。

void method2() {
    try {
        // Error here
    } catch(Exception e) {
        throw e;
    }
}

【讨论】:

    【解决方案2】:
        public void method1(){
            try {
                test2();
            } catch (IOException ex) {
                //catch test2() error
            }
        }
    
        public void method2() throws IOException{
    
        }
    

    使用投掷

    【讨论】:

      【解决方案3】:

      如果你在方法 2 的 catch 块中抛出另一个异常。

      public void method2() {
          try {
              // ...
          } catch(Exception e) {
              throw new NullPointerException();
          }
      }
      

      【讨论】:

        【解决方案4】:

        直到您通过添加 throw e; 将其重新放入您的 method2catch 块中之后才会出现。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-06-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-31
          相关资源
          最近更新 更多