异常处理机制
-
抛出异常
-
捕获异常
-
异常处理五个关键字
- try catch finally throw throws
-
基础的try catch finally
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");
}catch(Exception e){
System.out.println("Exception");
}catch(Throwable t){
System.out.println("Throwable");
} finally { //处理善后工作
System.out.println("finally");
}
//可以不要finally,finally一般在Io和资源处理里解决关闭工作的
}
public void a(){b();}
public void b(){a();}
}
- command+option+T快捷键和抛出异常
package exception;
public class Test2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
//mac 快捷键command+optin+T
try {
System.out.println(a/b);
} catch (Exception e) {
System.out.println("b不能为0");
System.exit(0);
e.printStackTrace();//打印错误的栈信息
} finally {
}
try {
new Test2().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
} finally {
}
}
//假设这个方法中处理不了这个异常,直接在方法上抛出异常
public void test(int a,int b) throws ArithmeticException {
if (b==0){//主动抛出异常,一般在方法中使用 throw
throw new ArithmeticException();
}
System.out.println(a/b);
}
}