search

Home  >  Q&A  >  body text

java-ee - 关于Java异常捕获的问题

如果捕获异常没有专门的处理,只是为了记录日志,那么异常究竟是这样

public void xxx() {
    try {
        ...
        ...
        ...
    } catch() {
        ...
    }
}

捕获好还是这样

public void xxx() {
    try {
        ...
    } catch() {
        ...
    }
    try {
        ...
    } catch() {
        ...
    }
    try {
        ...
    } catch() {
        ...
    }
}

捕获好,另外,是每一种异常单独捕获

public void xxx() {
    try {
        ...
        ...
        ...
    } catch(aaException e) {
        ...
    } catch(bbException e) {
        ...
    } catch(Exception e) {
        ...
    }
}

好,还是全部都用Exception捕获

public void xxx() {
    try {
        ...
        ...
        ...
    } catch(Exception e) {
        ...
    }
}

好?

PHPzPHPz2895 days ago422

reply all(7)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:53:10

    The more elegant way is to handle it through Aop, so that you don’t have to write repeated try and catch in the business code

    reply
    0
  • PHPz

    PHPz2017-04-18 09:53:10

    It’s better to use Exception

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 09:53:10

    Just to keep a log, the last one can explain the problem.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:53:10

    There is no need to subdivide the logs, printing the stack information is clear at a glance

    reply
    0
  • PHPz

    PHPz2017-04-18 09:53:10

    This depends on the scenario: In the third case, different exceptions are captured separately in order to handle the captured exceptions in a fine-grained manner, such as capturing cache exceptions, performing DB switching, capturing IO exceptions, and remediating them; fourth The first is to wrap an Exception and process it once, but some specific information will be lost
    My understanding is that dividing into so many exception types can be considered an extension of switch-case

    reply
    0
  • 黄舟

    黄舟2017-04-18 09:53:10

    This depends on the situation. If you don’t need to handle the exception, you can just replenish the exception at the low level. If you need to handle it, just catch the replenishment and handle it. For example, you can define your own prompt information for exceptions.

    reply
    0
  • 阿神

    阿神2017-04-18 09:53:10

    Just catch the exceptions you need to pay attention to. Other exceptions may be caught using Exception.

    reply
    0
  • Cancelreply