异常处理五个关键字:
try,catch,finally,throw,throws
测试案例1:捕获单个异常
package Exception;
public class Demo01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try { //try监控区
System.out.println(a/b);
} catch (Exception e) { //catch捕获异常
System.out.println("程序出现异常,变量b不能为0");
} finally { //用于处理善后工作,可以不写finally语句
System.out.println("Finally");
}
}
}
测试案例2:捕获多个异常
package Exception;
public class Demo01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
//捕获多个异常时,要从小到大捕获。Error < Exception < Throwable
try { //try监控区
System.out.println(a/b);
} catch (Error e) { //catch捕获异常
System.out.println("Error");
} catch (Exception e){
System.out.println("EXception");
} catch (Throwable t){
System.out.println("Throwable");
} finally { //用于处理善后工作,可以不写finally语句
System.out.println("Finally");
}
}
public void a(){
b();
}
public void b(){
a();
}
}
3.使用throw关键字在方法中主动抛出异常
package Exception;
public class Test02 {
public static void main(String[] args) {
new Test02().test(1,0);
}
public void test(int a,int b){
if(b==0){
throw new ArithmeticException();//主动抛出异常
}
System.out.println(a/b);
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-W2d0ISyc-1615372119807)(C:\Users\cheng zhimin\AppData\Roaming\Typora\typora-user-images\image-20210310174053799.png)]
4.使用throws关键字在方法上抛出异常
package Exception;
public class Test02 {
public static void main(String[] args) {
try { //使用throws关键字抛出的异常,需要用try...catch...语句捕获
new Test02().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
//假设在方法中无发处理这个异常,则需在方法山使用throws关键字在方法上抛出异常
public void test(int a,int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException();//主动抛出异常
}
System.out.println(a/b);
}
}
5.throw与throws的比较
(1)throws出现在方法函数头;而throw出现在函数体。
(2)throws表示出现异常的一种可能性,并不一定会发生这些异常;throw则是抛出了异常,执行throw则一定抛出了某种异常对象。
(3)两者都是消极处理异常的方式(这里的消极并不是说这种方式不好),只是抛出或者可能抛出异常,但是不会由函数去处理异常,真正的处理异常由函数的上层调用处理。
可以这么理解,throw是将方法体内的异常抛给方法,然后通过throws抛给其它方法
快捷键:Ctrl + Alt + t 可以快速生成try…catch…finally语句