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

前端 未结 3 331
后悔当初
后悔当初 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

    0 讨论(0)
  • 2021-01-20 06:41

    Because the existing exceptions may not be suitable for your situation. By creating your own exception you can make it easier to understand why the exception is thrown and it will stand out better than if you were using an existing exception.

    0 讨论(0)
  • 2021-01-20 06:53

    User defined exceptions can be much more descriptive.

    Example :

    public void setName (String name)
        throws NameException
    {
        if (name == null || name == "")
            throw new MissingNameException ();
        if (name.length > 30)
            throw new InvalidNameException (name); // this exception can contain a message that explains why the
                                                   // name is invalid and what a valid name looks like
        _name = name;
    }
    

    The alternative to creating your own exception is to use a predefined exception such as InvalidArgumentException, but that would give less information to the method that catches this exception (since it can be thrown by many methods in many classes).

    Defining a class hierarchy of exceptions gives the user of your classes better control when handling the exceptions.

    0 讨论(0)
提交回复
热议问题