异常处理机制
1.抛出异常
2.捕获异常
异常处理五个关键字
try、catch、finally、throw、throws
代码示例:
package com.exception;
public class Test {
public static void main(String[] args) {
int a=10;
int b=0;
try{//监控区域
System.out.println(a/b);
}catch(ArithmeticException e){//捕获异常 catch(想要捕获的异常类型)
System.out.println("程序出现异常,变量b不能为0");
}finally{//善后处理工作
System.out.println("finally");
}
}
}
输出示例
代码示例
package com.exception;
public class Test {
public static void main(String[] args) {
try{//监控区域
new Test().a();
}catch(Error e){//捕获异常 catch(想要捕获的异常类型)
System.out.println("程序出现异常,栈溢出");
}finally{//善后处理工作
System.out.println("finally");
}
}
public void a(){
b();
}
public void b(){
a();
}
}
输出示例
如果要捕获多个异常,异常从小到大
快捷键:control+alt+T
主动抛出异常一般用在方法中
代码示例:
package com.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 new ArithmeticException();
}
}
}
输出示例
假设这个方法中,处理不了这个异常,向上抛出异常(throws)代码示例:
package com.exception;
public class Test {
public static void main(String[] args) {
try {
new Test().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
public void test(int a,int b)throws ArithmeticException{
if(b==0){
throw new ArithmeticException();
}
}
}
输出示例: