Java中抛出和抛出的区别-澄清
对于何时使用投掷和何时使用投掷,我很困惑。请给我一个例子来说明两者的区别 此外,我还尝试了以下代码: 包装修改器 //导入java.io.IOException 公共类throweexceptions{Java中抛出和抛出的区别-澄清,java,Java,对于何时使用投掷和何时使用投掷,我很困惑。请给我一个例子来说明两者的区别 此外,我还尝试了以下代码: 包装修改器 //导入java.io.IOException 公共类throweexceptions{ int QAAutoLevel; int QAExp; void QAAutomationHiring(int grade) { if (grade<5) throw new ArithmeticException("Not professionally Qualifie
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);
}
<代码>int QAutoLevel;
国际QAExp;
自动招聘(国际级)
{
如果(gradeThrow实际返回异常,而throws是编译器的一个符号,则此方法可能返回异常 在上面的代码中,如果分数低于5,将创建并返回异常算术异常,这是您第二次调用QAFerience时的情况。
由于调用方法调用的方法(返回异常)未插入catch块,因此它也将停止执行并返回主方法。由于主方法也未捕获异常,因此它将与其他方法一样停止执行并返回异常。这就是为什么
t.checkThrowsExp
w我不会被执行。throws
用于告诉人们
警告:此方法/构造函数很有可能引发xxxeexception
和YYYException
!请确保您能够处理它们
例如:
Thread.sleep
方法声明为:
public static native void sleep(long millis) throws InterruptedException;
正如您所看到的,throws
关键字告诉人们sleep
很可能抛出InterruptedException
。因此,您必须用try catch
包围方法调用,或者用throws InterruptedException
标记调用方方法。之后的异常抛出yword通常是“检查”异常,这些异常是由程序无法直接控制的区域内的无效条件引起的,如无效用户输入、数据库问题等
请注意,标记为的方法可能从不抛出XXXException
另一方面,抛出实际上抛出异常
throw new RuntimeException("Something went wrong!");
每当代码执行到达该语句时,无论发生什么情况,都将抛出异常,并且该方法将返回
简而言之,throw
实际上是抛出,而throws
只是说可能会抛出异常(事实上,这是错误的).throw
在您想要抛出异常时使用。throws
为方法声明抛出哪些潜在的异常
,以便调用者知道捕获什么。非常感谢!我尝试在main中的qaperience函数之前调用checkThrowsExp函数,并得到显示的消息对于算术异常。此外,我尝试在QAutomationHiring函数中的抛出异常周围添加try和catch块。这将显示异常消息并继续执行下一步的语句。现在我明白了要点。