捕获和抛出异常
- 抛出异常
- 捕获异常
- 关键词:try,catch,finally,throw,throws
- 功能介绍:
- try:监控区域
- catch:想要捕获的异常类型
- finally:处理善后工作,一定执行
- throw:多在方法内使用
- 用法:
throw new ArithmeticException(); //ArithmeticException()可替换
- throws:在方法的声明定义处使用
- 用法:
public void test(int a, int b) throws ArithmeticException{}
-
try-catch-finally代码示例:
-
若要捕获多个异常,需从小到大
package Exception;
public class Demo01 {
public static void main(String[] args) {
int a = 10;
int b = 0;
//若要捕获多个异常,需从小到大
try { //try监控区域
System.out.println(a/b);
}catch(ArithmeticException e){ //想要捕获的异常类型
System.out.println("除数b不能为0");
}catch (Error e){
System.out.println("Error");
}catch (Exception e) {
System.out.println("Exception");
}catch (Throwable t){
System.out.println("Throwable");
} finally{ //处理善后工作
System.out.println("善后工作,finally中的语句一定执行");
}
/*
输出结果:
除数b不能为0
善后工作,finally中的语句一定执行
*/
}
}
- throw代码示例:
package Exception;
public class Demo02 {
public static void main(String[] args) {
int a = 10;
int b = 0;
new Demo02().test(a,b);
}
public void test(int a, int b){
if(b==0){
throw new ArithmeticException();
}
System.out.println("a/b"); //抛出后这里不执行
}
}
- throws代码示例:
package Exception;
public class Demo02 {
public static void main(String[] args) {
int a = 10;
int b = 0;
try {
new Demo02().test(a,b);
} catch (ArithmeticException e) {
System.out.println("除数不能为0");
} finally {
System.out.println("善后区域");
}
}
public void test(int a, int b) throws ArithmeticException{
System.out.println(a/b); //抛出后这里不执行
}
/*
输出结果:
除数不能为0
善后区域
*/
}