0

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

以以下代码为例:

//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 ? 
}
4

4 回答 4

2

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

找到编写自定义异常的最佳实践。

于 2014-07-24T08:53:34.033 回答
0

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

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

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

这样,除了在 String 中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"
}
于 2014-07-24T08:57:32.487 回答
0

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

现在假设我们只有一个异常,那么当异常被抛出时,我们怎么知道会发生什么错误呢?毕竟,名字很重要。

于 2014-07-24T08:56:23.163 回答
-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
于 2019-03-12T14:14:20.943 回答