为什么用户定义的异常类在java中是首选的/重要的? [英] Why user defined exception classes are preferred/important in java?

查看:316
本文介绍了为什么用户定义的异常类在java中是首选的/重要的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们在Java中使用System定义的异常类时,为什么需要进行用户定义的异常类?因为我的老师告诉我在我的项目中进行异常课程。



任何精心设计的例子都会很好。

解决方案

用户定义的异常可以更加描述。



示例:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆