Why user defined exception classes are preferred/important in java?

前端 未结 3 380
后悔当初
后悔当初 2021-01-20 06:09

When we have System defined exception classes in Java, then why there is need to make user defined exception classes? Because my teacher told me to make Exception classes in

3条回答
  •  遇见更好的自我
    2021-01-20 06:38

    There are a few reasons to have user defined exceptions:

    1. You want to pass along extra information such as error codes. For example, if you are a database vendor, you can add extra methods to include your internal error codes.
    2. To add more specific Exception types so you don't need to rely on parsing the exception message which could change over time. For example, Hibernate has ConstraintViolationException. You know immediately that you have a problem with some kind of constraint on the database (probably foreign key constraint).
    3. You can handle different Exceptions differently with different catch blocks.

    Having said that, in general you should prefer to use the built in Exceptions or at least have your custom Exceptions extend the built-ins so users don't have to care about your special classes unless they want to.

    For more info about why you should prefer the built-in exceptions see Effective Java Item 60: Favor the use of standard exceptions

提交回复
热议问题