Error和Exception
扑获和抛出异常
异常处理的五个关键词:
try、 catch 、finally、throw、throws
基本的扑获和抛出异常
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {//try监控区域
if (b==0){
throw new ArithmeticException();//主动抛出异常,一般在方法中使用
}
System.out.println(a/b);
}catch (ArithmeticException e){//catch捕获异常
System.out.println("程序出现异常,变量b不能为0");
}finally {//处理善后工作
System.out.println("finally");
}
//finally可以不要,一般用于关闭IO、资源
//假设要捕获多个多个异常,从小到大
}
}
快捷键扑获和抛出异常
public class Test1 {
public static void main(String[] args) {
int a = 1;
int b = 0;
//option+command+T
try {
System.out.println(a/b);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
方法中主动扑获和抛出异常
public class Test2 {
public static void main(String[] args) {
Test2 t = new Test2();
try {
t.test(1,0);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
public void test(int a,int b){
if (b==0){
throw new ArithmeticException();
}
}
}