【发布时间】: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