如何在java中传播异常

Sur*_*dhi 10 java exception propagation

我是一名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.
   }
   }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Jon*_*eet 23

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

public void myMethod() throws ExceptionType1, ExceptionType2 {
    // Some code here which can throw exceptions
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

不是一个好主意,有catch块这只是重新抛出异常-除非有一些微妙的原因(例如,以防止处理它更一般的catch块)通常应该只是删除catch块来代替.