【问题标题】:what is the difference between throwing a new exception within a body of a method and throwing the exception in the header of the method [duplicate]在方法的主体中抛出新异常和在方法的标头中抛出异常有什么区别[重复]
【发布时间】:2016-04-28 07:38:08
【问题描述】:

您好,我想知道相同方法的两种变体之间的区别和相似之处。

public string test(String value)
throw new testException();

public abstract String test(String value) throw new testException;

如果我的语法错误,请原谅我。

【问题讨论】:

    标签: java exception throw throws


    【解决方案1】:
    public abstract String test(String value) throw new testException;
    

    没有意义。你能做的最接近的事情就是写

    public abstract String test(String value) throws testException;
    

    这表明test 是一个可以抛出testException 的方法。如果testException 不是RuntimeException,那么必须这样声明。但是在方法签名中添加throws testException 只是表示方法可以抛出该异常,它实际上并没有抛出异常。

    【讨论】:

    • 完美,谢谢,现在这很有意义,我认为因为它是抽象的,所以会遇到问题。 @路易斯
    • @user5647516 你应该接受路易斯的回答
    • @GregHilston 我可以再过 5 分钟 :)
    【解决方案2】:

    在 java 中,每个方法都应使用以下语法指示它们是否抛出异常:

    public String test(String value) throws testException
    {
       //your code here
       //at some point you will throw the exception like this:
       throw new testException();
    }
    

    如果你使用抽象方法,方法签名只需要包含throws表达式,但是当你实现方法时,你需要在方法体中添加throw语句。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      相关资源
      最近更新 更多