用户定义的异常的实现

问题描述 投票:0回答:4

我一直在网上搜索并研究一些书籍,但给出的例子是有限的,我仍然对用户定义的例外有一些疑问。

使用以下代码作为示例:

//Conventional way of writing user-defined exception
class IdException extends Exception  

{
    public IdException(String s)
    {
        super(s);
    }   
}

class Product
{
    String id = new String();
    public Product(String _id) throws IdException
    {
        id = _id;

        //Check format of id
        if (id.length() < 5)
            throw(new IdException(_id));
    }
}

似乎编写用户定义的异常的传统方式几乎总是相同的。在用户定义的异常的构造函数中,我们总是调用super(msg)。这引发了一个问题:如果以这种方式实现大多数异常,那么所有这些异常之间有什么区别?

例如,我可以有多个用户定义的异常,但所有似乎都做同样的事情,没有任何差异。 (这些例外中没有实现,是什么让它们起作用?)

例:

class IdException extends Exception
{
    public IdException(String s)
    {
        super(s);
    }   
}

class NameException extends Exception
{
    public NameException(String s)
    {
        super(s);
    }   
}

class ItemException extends Exception
{
    public ItemException(String s)
    {
        super(s);
    }   
}

QUE:我们不应该(例如)在异常类中实现id的检查吗?如果不是所有异常类似乎都做同样的事情(或者没有做任何事情)。

在异常中实现检查的示例:

class IdException extends Exception     {
    public IdException(String s)
    {
        super(s);
        //Can we either place the if-statements here to check format of id ?
    }
    //Or here ? 
}
java exception user-defined
4个回答
2
投票

理想情况下,您不应在Exception中实现业务逻辑。 Exception告知有关异常行为的信息。在Custom Exception中,您可以自定义该信息。

找到best practice来编写自定义异常。


0
投票

我们已经在java中定义了很多异常。所有人都做同样的事情:to notify user about the problem in code

现在假设我们只有一个异常,那么抛出异常时我们怎么能发生错误。毕竟,名字很重要。


0
投票

以您的示例Exceptions为例,我将通过格式化提供的数据来创建更精细的消息:

public IdException(String id, String detail) {
    super(String.format("The id \"%s\" is invalid: %s", id, detail));
}

throw new IdException(_id, "Id too short.");

这样,除了在IdException字符串中提供给定值(id)和详细消息之外,e.getMessage()类中没有真正的逻辑,因此调试和日志记录很容易阅读,代码本身也很简单:

Id _id有问题,即它太短了。因此我们把它扔回来电。

此外,当您在代码中抛出不同类型的异常时,它允许调用者代码以不同方式处理每个异常类型:

try {
    getItem(id, name);
} catch (IdException ex) {
    fail(ex.getMessage()); // "The Id is bogus, I don't know what you want from me."
} catch (NameException ex) {
    warn(ex.getMessage()); // "The name doesn't match the Id, but here's the Item for that Id anyways"
} catch (ItemException ex) {
    fail("Duh! I reported to the dev, something happened");
    emailToAdmin(ex.getMessage()); // "The Item has some inconsistent data in the DB"
}

-1
投票
class MyException extends Exception{
       int x;
       MyException(int y) {
         x=y;
       }
       public String toString(){
         return ("Exception Number =  "+x) ;
      }
    }

    public class JavaException{
       public static void main(String args[]){
      try{
           throw new MyException(45);

      }
     catch(MyException e){
        System.out.println(e) ;
     }
    }
}

output: Exception Number = 45
© www.soinside.com 2019 - 2024. All rights reserved.