如何在Java中传播异常 [英] How to propagate an exception in java

查看:176
本文介绍了如何在Java中传播异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am a C programmer and just learning some java recently because I am developing one android application. Currently I am in a situation. Following is the one.

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

Now I wan to use call the method MyMethod() somewhere else in another class. If some one can provide me some code snippet how to propagate the exceptions to the caller of MyMethod() so that I can display them in a dialog box in the caller method.

对不起,如果我对这个问题的回答不太清楚和奇怪。

Sorry If I am not so much clear and weird in the way of asking this question.

推荐答案

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

Just don't catch the exception in the first place, and change your method declaration so that it can propagate them:

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

如果您需要采取一些措施然后然后传播,可以将其重新抛出:

If you need to take some action and then propagate, you can rethrow it:

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

此处 ExceptionType2 根本不会被捕获-它只会自动传播。 ExceptionType1 被捕获,记录并重新抛出。

Here ExceptionType2 isn't caught at all - it'll just propagate up automatically. ExceptionType1 is caught, logged, and then rethrown.

不是拥有只是会抛出异常的catch块-除非有一些微妙的原因(例如,防止更通用的catch块进行处理),否则通常应删除该catch块。

It's not a good idea to have catch blocks which just rethrow an exception - unless there's some subtle reason (e.g. to prevent a more general catch block from handling it) you should normally just remove the catch block instead.

这篇关于如何在Java中传播异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆