Java - where and how should exceptions be used?

前端 未结 9 1466
天涯浪人
天涯浪人 2021-01-02 05:03

I was reading some things about exception handling in Java, to be able to write better code. OK, I admit, I am guilty; I\'ve used too much try-catch{} blocks, I\'ve used

9条回答
  •  情话喂你
    2021-01-02 05:11

    1. While I don't have any numbers, I don't believe that try-catch has any significant impact on performance (not that I have seen). I think that if you don't run into many exceptions, the performance impact will be basically nothing. But in any case, it's best to care about implementing code correctly first and achieving good performance second -- a lot easier to do the second once the first is done.

    2. I think the exception class should be specific as to what the exception really is. The problem I have with Java's SQLExceptions is that they give you no information about what really went wrong. Spring uses far a set of more descriptive database exceptions (deadlock exceptions, data integrity exceptions, etc.) That way you can tell what the problem really was.

    3. Checked exceptions can be annoying, but I don't think they're always bad. For example, Spring uses unchecked exceptions for database errors, but I still check for them and either 1) handle them right there, if possible, or 2) wrap in a more general exception that the shows that the component failed.

    4. Unfortunately, I can't think of any good specific exceptions. However, like I said, I've found Spring's exception rules to be helpful and yet not annoying, so maybe you could look at some Spring docs. The Spring database classes are a good example.

提交回复
热议问题