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

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

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题