Java - where and how should exceptions be used?

前端 未结 9 1489
天涯浪人
天涯浪人 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:14

    One thing that we have done on our team is to have custom exceptions for our errors. We are using the Hibernate Validator framework, but you can do this with any framework, or stock exceptions.

    For example, we have a ValidationException to handle validation errors. We have a ApplicationException to handle system errors.

    You DO want to minimize your try-catch-ing. In our case, we will have the validator collect ALL the validations in "InvalidValue" objects, and then throw a single ValidationException with the invalid value information bundled into it. Then you can report to the user which fields were in error, etc.

    In the case you mentioned of a database error - you may not want to send the stacktrace to the UI (logging it is a good idea). This is a case where you can catch the database exception, then throw your own ApplicationException to your GUI. Your GUI won't have to know how to deal with an infinite number of server errors, but can be set to deal with the more generalized ApplicationException - possibly reporting that there is a problem with the server, and indicating that the user should contact your customer support department to report the problem.

    Lastly, sometimes you can't help but use a lot of try/catch blocks because of the external APIs you rely on. This is fine. As mentioned before, catch the external exception, and format it into one which makes more sense to YOUR application. Then throw the custom exception.

提交回复
热议问题