[英]Why user defined exception classes are preferred/important in java?
When we have System defined exception classes in Java, then why there is need to make user defined exception classes? 当我们在Java中有系统定义的异常类时,为什么需要创建用户定义的异常类? 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). 创建自己的异常的替代方法是使用预定义的异常,例如InvalidArgumentException
,但这会为捕获此异常的方法提供更少的信息(因为它可以被许多类中的许多方法抛出)。
Defining a class hierarchy of exceptions gives the user of your classes better control when handling the exceptions. 定义异常的类层次结构可以在处理异常时更好地控制类的用户。
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. 通过创建自己的异常,您可以更容易理解抛出异常的原因,并且与使用现有异常相比,它会更好。
There are a few reasons to have user defined exceptions: 用户定义的异常有几个原因:
ConstraintViolationException
. 例如,Hibernate具有ConstraintViolationException
。 You know immediately that you have a problem with some kind of constraint on the database (probably foreign key constraint). 您立即知道您对数据库存在某种约束问题(可能是外键约束)。 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. 话虽如此,一般来说,您应该更喜欢使用内置的Exceptions,或者至少让您的自定义Exceptions扩展内置插件,这样用户就不必关心您的特殊类,除非他们愿意。
For more info about why you should prefer the built-in exceptions see Effective Java Item 60: Favor the use of standard exceptions 有关您为什么更喜欢内置异常的详细信息,请参阅Effective Java Item 60:赞成使用标准异常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.