Why is user-defined exception class preferred / important in Java?

When we have system defined exception classes in Java, why do we need to create user-defined exception classes? Because my teacher told me to make abnormal courses in my project

Any elaborate example will be good

Solution

User - defined exceptions can be 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;
}

An alternative to creating your own exception is to use a predefined exception, such as invalidargumentexception, but this will provide less information for the method that caught the exception (because it can be thrown by many methods in many classes)

Defining the class hierarchy of exceptions can better control the users of the class when handling exceptions

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>