如何在java中传播exception

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

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

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

 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被捕获,记录,然后重新抛出。

拥有重新抛出exception的catch块并不是一个好主意 – 除非有一些微妙的原因(例如,为了防止更常规的catch块处理它),你通常应该只删除catch块。

不要抓住它并再次重新抛出。 只需这样做,并在你想要的地方捕捉它

 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 } } 

只需重新抛出exception即可

throw Excp1;

您需要将exception类型添加到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 ,因为你不再处理exception,除非你在catch语句中添加一些额外的代码,然后在重新抛出它之前处理exception。

我总是这样做:

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