为什么用户定义的异常类在java中是首选的/重要的? [英] Why user defined exception classes are preferred/important in java?
问题描述
任何精心设计的例子都会很好。
用户定义的异常可以更加描述。
示例:
public void setName(String name)
throws NameException
{
if(name == null || name ==)
throw new MissingNameException();
if(name.length> 30)
throw new InvalidNameException(name); //这个异常可以包含一个消息,解释为什么
//名称无效,有效名称如
_name = name;
}
创建自己的异常的替代方法是使用预定义的异常,例如 InvalidArgumentException
,但这将给捕获此异常的方法提供更少的信息(因为它可以在许多类中被许多方法抛出)。
定义异常的类层次结构可以让您的类的用户在处理异常时更好地控制。
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 my project.
Any elaborate example will be good.
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.
这篇关于为什么用户定义的异常类在java中是首选的/重要的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!