【问题标题】:How to propagate an exception in java如何在java中传播异常
【发布时间】:2012-03-18 22:40:09
【问题描述】:

我是一名 C 程序员,最近刚刚学习了一些 Java,因为我正在开发一个 Android 应用程序。目前我处于一种情况。以下是一个。

public Class ClassA{

public ClassA();

public void MyMethod(){

   try{
   //Some code here which can throw exceptions
   }
   catch(ExceptionType1 Excp1){
   //Here I want to show one alert Dialog box for the exception occured for the user.
   //but I am not able to show dialog in this context. So I want to propagate it
   //to the caller of this method.
   }
   catch(ExceptionType2 Excp2){
   //Here I want to show one alert Dialog box for the exception occured for the user.
   //but I am not able to show dialog in this context. So I want to propagate it
   //to the  caller of this method.
   }
   }
}

现在我想在另一个类的其他地方调用 MyMethod() 方法。如果有人可以提供一些代码 sn-p 如何将异常传播给 MyMethod() 的调用者,以便我可以在调用者方法的对话框中显示它们。

对不起,如果我问这个问题的方式不是那么清楚和奇怪。

【问题讨论】:

标签: java exception propagation


【解决方案1】:

只需重新抛出异常

throw Excp1;

您需要像这样将异常类型添加到MyMthod() 声明中

public void MyMethod() throws ExceptionType1, ExceptionType2  {

   try{
   //Some code here which can throw exceptions
   }
   catch(ExceptionType1 Excp1){
       throw Excp1;
   }
   catch(ExceptionType2 Excp2){
       throw Excp2;
   }
}

或者完全省略 try,因为您不再处理异常,除非您在 catch 语句中添加一些额外的代码,在重新抛出异常之前处理异常。

【讨论】:

    【解决方案2】:

    首先不要捕获异常,并更改您的方法声明,以便它可以传播它们:

    public void myMethod() throws ExceptionType1, ExceptionType2 {
        // Some code here which can throw exceptions
    }
    

    如果你需要采取一些行动并然后传播,你可以重新抛出它:

    public void myMethod() throws ExceptionType1, ExceptionType2 {
        try {
            // Some code here which can throw exceptions
        } catch (ExceptionType1 e) {
            log(e);
            throw e;
        }
    }
    

    这里 ExceptionType2 根本没有被捕获 - 它只会自动传播。 ExceptionType1 被捕获、记录,然后被重新抛出。

    不是让 catch 块只是重新抛出异常是个好主意 - 除非有一些微妙的原因(例如,为了防止更通用的 catch 块处理它)您通常应该只删除 catch 块。

    【讨论】:

      【解决方案3】:

      不要抓住它并再次抛出。只需这样做并在您想要的地方抓住它

      public void myMethod() throws ExceptionType1, ExceptionType2 {
          // other code
      }
      

      例子

      public void someMethod() {
          try {
              myMethod();
          } catch (ExceptionType1 ex) {
              // show your dialog
          } catch (ExceptionType2 ex) {
              // show your dialog
          }
      }
      

      【讨论】:

        【解决方案4】:

        我总是这样:

        public void MyMethod() throws Exception
        {
            //code here
            if(something is wrong)
                throw new Exception("Something wrong");
        }
        

        那么当你调用函数时

        try{
            MyMethod();
           }catch(Exception e){
            System.out.println(e.getMessage());
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-06-28
          • 2010-11-29
          • 1970-01-01
          • 1970-01-01
          • 2021-01-28
          • 2018-06-08
          • 1970-01-01
          相关资源
          最近更新 更多