12

我是一名 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() 方法。如果有人可以为我提供一些代码片段,如何将异常传播给 MyMethod() 的调用者,以便我可以在调用者方法的对话框中显示它们。

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

4

4 回答 4

26

只是不要一开始就捕获异常,并更改您的方法声明,以便它可以传播它们:

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

于 2012-02-29T12:33:57.707 回答
2

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

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
    }
}
于 2012-02-29T12:35:38.390 回答
0

我总是这样做:

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());
}
于 2013-05-12T10:50:11.137 回答
0

只需重新抛出异常

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 语句中添加一些额外的代码来处理异常,然后再重新抛出它。

于 2012-02-29T12:31:47.073 回答