首页 > 其他分享 >Demo70_throw与throws

Demo70_throw与throws

时间:2022-11-09 22:55:20浏览次数:38  
标签:Demo70 代码 System throws try println throw out

//throw与throws
package com.YiChang;

public class E_D {
public static void main(String[] args) {
//new E_D().A(10,0);如果用throw或者throws万一出现异常就是停止执行接下来的代码
System.out.println("111");
//为什么要用try和catch再进行监控,捕获呢?
//因为使用try catch的话那么运行时出现了异常还是能:继续正常输出接下来的代码
//如果不使用try将匿名代码块包裹起来的话,那么接下来的代码就会不执行
try {
new E_D().A(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();//抛出异常
System.out.println("使用try,catch");
} finally {
System.out.println("程序结束~");
}
System.out.println("就算出现异常还是会接下来输出后面的代码");
}
//假设这个方法中处理不了这个异常,那就在方法上抛出异常
public void A(int a,int b) throws ArithmeticException{
System.out.println("11");
//如果b==0那么就抛出这个异常
if (b==0){
throw new ArithmeticException();//主动抛出异常,一般都是用在方法中使用
}
//就算没有System.out.println(a/b);也是会主动抛出异常
//System.out.println(a/b);
System.out.println("110");//第30行代码
//因为这个方法是throw所以当有异常出现的时候,接下来的代码它不执行(第30行代码)
}
}
/*
如果是try catch的话那么运行时出现了异常还是能:继续正常输出接下来的代码
如果是使用throw或者throws的话那么在运行中出现了异常就会:停止输出接下来的代码
*/
控制台输出的结果如下

 这些红字就是抛出的异常

ctrl alt+t:快速打出try与catch代码块

标签:Demo70,代码,System,throws,try,println,throw,out
From: https://www.cnblogs.com/CHX249/p/16875524.html

相关文章