2012-02-29 73 views
6

我是C程序员,最近刚学习一些java,因为我正在开发一个android应用程序。目前我处于一种状况。以下是一个。如何在java中传播异常

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()的调用者,以便我可以在调用方法的对话框中显示它们。

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

+1

参见http://stackoverflow.com/questions/409563/best-prac tices换异常管理功能于Java的或-C-尖锐 – mglauche 2012-02-29 12:34:45

回答

20

只要不赶摆在首位之外,并改变你的方法声明,以便它可以传播他们:如果你需要采取一些行动,然后繁殖

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块,而不是。

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语句中执行一些额外的代码。

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 
    } 
} 
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()); 
}