如何处理java方法中的多个异常? [英] How to handle multiple exceptions in a java method?

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

问题描述

我已经阅读这不是处理像这样的多个异常的最佳实践:

I've read It isn't a best practice to handle multiple Exceptions like this:

public void myMethod() throws ExceptionA, ExceptionB, ExceptionC {
    //more code here
}

然后调用myMethod():

And then to call myMethod():

try {
    myObject.myMethod();
} catch(Exception e) {
    //More code here
}

尽管异常是所有其他异常的父类,但它是一个不好的做法。但是,在我的应用程序中,我使用的是Java SE 6,我需要:

Despite Exception is the parent class of all the other exceptions, it is consider a bad practice. But, in my application I'm using java SE 6 and I need to:


  • 做文件操作可能意味着FileNotFOundException和IOException

  • Marshal对象(为了创建XML文件)JAXBException

  • 创建一个pdf文件(使用pdfbox库)COSVisitorException

  • 使用JavaMail发送邮件,MessagingException

  • Do File operations that can imply a FileNotFOundException and IOException
  • Marshal objects (in order to create XML files) JAXBException
  • Create a pdf file (using pdfbox library) COSVisitorException
  • Send an email using JavaMail, MessagingException

最简单的方法是在方法声明中添加一个throws语句,但是可以编写客户端方法的正确方法?

The easiest way is to add a throws statement in method declaration, but what could be the proper way to write the client method?

添加6或7个catch块可以处理所有可能的异常吗?

Is it OK to add 6 or 7 catch blocks to handle all the possible exceptions?

推荐答案

一般来说(对于Java 6及以下),您应该单独处理每个异常...

Generally speaking (for Java 6 and below), you should handle each exception individually...

try {
    myObject.myMethod();
} catch (ExceptionA e) {
    // Condition for A
} catch (ExceptionB e) {
    // Condition for B
} catch (ExceptionC e) {
    // Condition for C
}

这允许您处理每个异常根据它是什么,但也意味着您只处理报告的方法引发的异常

This allows you to handle each exception differently based on what it is, but also means you are only handling those exceptions reported to be thrown by the method

在Java 7+中,您可以使用多-catch或combined catch(我们找不到官方)

In Java 7+ you can make use of "multi-catch" or "combined catch" (we can't find an "official" term)

try {
    myObject.myMethod();
} catch (ExceptionA | ExceptionB | ExceptionC e) {
    // Condition for A and B and C
}

但即使如此,您应该将异常集中在常见使用组中

But even then, you should be focusing exceptions into "common" use groups

try {
    myObject.myMethod();
} catch (ExceptionA | ExceptionB e) {
    // Condition for A and B
} catch (ExceptionC e) {
    // Condition for C
}

另一个选项,如果您控制如何定义异常,则是从普通基础异常扩展这个例子就是 FileNotFoundException ,它从 IOException 中扩展,由 FileReader抛出 FileInputStream (作为示例),这意味着您可以将 FileNotFoundException

Another option, if you control how the exceptions are defined, is to extend from a common base exception, a good example of this is the FileNotFoundException which extends from the IOException, which is thrown by FileReader and FileInputStream (as examples), this means you can handle the FileNotFoundException as a common IOException should you wish...

FileReader fr = null;
try {
    fr = new FileReader(new File(...));
    // Read from reader...
} catch (IOException exp) {
    // Common catch block
} finally {
    // Best attempt to close
    try {
        fr.close();
    } catch (Exception exp) {
    }
}

或者您可以处理 FileNotFoundException ,因为它是自己的条件...

Or you could handle the FileNotFoundException as it's own condition...

FileReader fr = null;
try {
    fr = new FileReader(new File(...));
    // Read from reader...
} catch (FileNotFoundException exp) {
    // File not found condition
} catch (IOException exp) {
    // Other IO condition
} finally {
    // Best attempt to close
    try {
        if (fr != null) {
            fr.close();
        }
    } catch (Exception exp) {
    }
}

这允许您将像一样的异常组合在一起,但是还可以为您提供控件,以便在需要时定义更细粒度的条件...

This allows you to either group "like" exceptions together, but also provides you with the control to define more fine grained conditions should you need to...

请注意,我们上面的例子,如果我首先把 IOException ,那么 FileNotFoundException 永远不会被处理,在执行此操作时,请确保您首先使用最低/最严格/最优异的异常,因为它们按您列出的顺序顺序处理

Beware though, we the above example, if I put the IOException first, the FileNotFoundException would never be handled, when doing this, make sure that you use the lowest/tightest/finest exceptions first, as they are processed sequentially in the order you have listed

另一个选项不喜欢,但已经看到)可能是抓住一个共同的祖先,然后比较实际的类型,这将允许您为某些子类型的异常提供常见的处理程序。

Another option (which I'm not keen on, but have seen) might be to catch a "common" ancestor and then compare the actual type, which would allow you to provide common handlers for some sub-type of the exception.

} catch (IOException exp) {
    if (exp instanceof FileNotFound || exp instanceof FileSystemException) {   
        // Common handling
    } else {
        // Generic handling
    }
}

这可能有助于在该方法仅抛出祖先类型(即 IOException ),但是您需要提供更精细的分辨率

This might be helpful in situations where the method only throws the ancestor type (ie IOException), but you need to provide a more fine grained resolution

但是,再次,我将专注于仅处理声明为抛出的预期的常见异常,不要调用 Throwable ,例如

But, again, I would be focused on only handling the expected "common" exceptions declared as been thrown, don't be tempered to catch Throwable for example

这篇关于如何处理java方法中的多个异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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