捕获和抛出异常
异常处理五个关键字
try , catch , finally , throw , throws
try catch finally(快捷键:选中要要监控的代码语句 快捷键: ctrl + alt + t)
package exception;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try{//try 监控区域
System.out.println(a/b);
}catch (ArithmeticException e){//catch 捕获异常
System.out.println("程序出现异常,b不能为0");
}finally {// 处理善后工作
System.out.println("finally");
}
//finally 可以不要finally, 用: 假设IO,资源需要关闭
}
}
---------------------------------------------------------------------------------------------------
// 选中要要监控的代码语句 快捷键: ctrl + alt + t
package exception;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
// 假设要捕获多个异常: 异常类型:从小到大
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 {// 处理善后工作
System.out.println("finally");
}
//finally 可以不要finally, 用: 假设IO,资源需要关闭
}
}
throw throws
package exception;
public class Test {
public static void main(String[] args) {
new Test().test(1,0);
}
public void test(int a , int b){
if(b==0){// throw throws
throw new ArithmeticException();//主动抛出异常,一般在方法中使用 throw
}
System.out.println(a/b);
}
}
---------------------
package exception;
public class Test {
public static void main(String[] args) {
try {
new Test().test(1,0); // try catch
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
// 假设这个方法中,处理不了这个异常。方法上抛出异常
public void test(int a , int b) throws ArithmeticException{ // throws
if(b==0){// throw throws
throw new ArithmeticException();//主动抛出异常,一般在方法中使用
}
System.out.println(a/b);
}
}
学习内容源自视频:b站狂神说Java