【问题标题】:Difference between Throw and Throws in Java- Clarification [duplicate]Java中Throw和Throws之间的区别-澄清[重复]
【发布时间】:2016-12-21 09:41:44
【问题描述】:

我很困惑,不清楚何时使用 throw 和 throws 。请给我一个例子来说明差异。

另外,我尝试了以下代码:

包 AccessModifiers;

//导入java.io.IOException;

公共类 ThrowExceptions {

int QAAutoLevel;
int QAExp;

void QAAutomationHiring(int grade)
{
    if (grade<5)
    throw new ArithmeticException("Not professionally Qualified");  
    else
        System.out.println("Ready to be test");

}

void QAExperience(int x,int grade)
{

        QAAutomationHiring(grade);


}

void checkThrowsExep(int a,int b) throws ArithmeticException
{
    try{
    int result=a/b;
    System.out.println("Result is :"+result);
    }
    catch(Exception e)
    {
        System.out.println("The error messgae is: "+ e.getMessage());
    }
}

public static void main(String args[])
{
    ThrowExceptions t=new ThrowExceptions();
    //t.QAAutomationHiring(8);
    t.QAExperience(2,8);
    t.QAExperience(4,2);

    t.checkThrowsExep(5, 0);

}

}

在上面的代码中,当我运行程序时,没有到达 main 函数中的“t.checkThrowsExp”行。我研究了 throw 和 throws 用于捕获异常并继续执行程序。但是在这里执行停止并且不继续执行下一组语句。请分享您的 cmets。

【问题讨论】:

  • throw 在你想抛出异常时使用。 throws 为方法声明什么潜在的Exceptions 被抛出,以便调用者知道要捕获什么。

标签: java


【解决方案1】:

throws 用于告诉人们这一点

警告:这个方法/构造函数很有可能抛出XXXExceptionYYYException!请务必处理好它们!

例子:

Thread.sleep 方法声明为:

public static native void sleep(long millis) throws InterruptedException;

如您所见,throws 关键字告诉人们sleep 很可能会抛出InterruptedException。因此,您必须用try-catch 包围方法调用或用throws InterruptedException 标记调用方方法。 throws 关键字之后的异常通常是“已检查”异常,它们是由程序直接控制之外的区域中的无效条件引起的,例如无效的用户输入、数据库问题等。

请注意,标有throws XXXExcepion 的方法可能永远不会抛出XXXException

throw,另一方面,实际上 抛出了异常。可以这样使用

throw new RuntimeException("Something went wrong!");

而且只要代码执行到这个语句,无论如何都会抛出异常,方法返回。

简而言之,throw 实际上是在抛出,而throws 只是可能会抛出异常(实际上是错误的) .

【讨论】:

    【解决方案2】:

    Throw 实际上会返回异常,而 throws 是向编译器发出的信号,表明此方法可能会返回异常。

    在您上面的代码中,如果等级低于 5,将创建并返回异常 ArithmeticException,这是您第二次调用 QAExperience 时的情况。 由于调用返回异常的方法的调用方法不在catch 块中,因此它也将停止执行并返回主方法。由于 main 方法也不会捕获异常,因此它会像其他方法一样停止执行并返回异常。这就是为什么t.checkThrowsExp不会被执行的原因。

    【讨论】:

    • 非常感谢!我尝试在 main 中的 QAExperience 函数之前调用 checkThrowsExp 函数,我得到了 ArithmeticException 显示的消息。
    • 另外,我尝试在 QAAutomationHiring 函数中的 throw 异常周围添加 try 和 catch 块。这将显示异常消息并继续执行下一步的语句。现在我明白了。
    猜你喜欢
    • 2014-10-26
    • 2020-08-03
    • 2018-08-18
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 2011-04-23
    相关资源
    最近更新 更多