在理想的情况下,我们的程序会按照我们的思路去运行,按理说是不会出现问题的,但是,代码实际编写后并不一定是完美的,可能有我们考虑不到的情况,如果这些情况正常得到一个错误的结果还好,但如果直接导致程序运行出现问题了呢?
-
异常的类型:
运行时异常(RuntimeException):在编译阶段无法感知代码是否出现问题,只有在运行时候才知道会不会出错,这样的异常称之为运行异常。(空指针异常、类型转换异常)
运行时异常或者是运行时异常的子类直接抛出就行
public class Main {
public static void main(String[] args){
test(1,0);
}
private static int test(int a,int b){
if(b==0) throw new ArithmeticException("除数不能为0");
return a/b;
}
}
-
编译时异常(Exception):(要处理在方法最后对抛出异常进行声明)
我们必须告诉函数的调用方我们会抛出某个异常,调用方必须要对抛出的异常进行处理才可以。在函数体中如果没有异常的话可以不用在函数方法的后面声明。
public class Main { public static void main(String[] args){ //抛出异常的声明 private static int test(int a,int b) throws Exception { if(b==0) throw new Exception("除数不能为0"); return a/b; } }
-
异常的处理: try-catch语句
运行时异常,根据选择,可以不进行try-catch处理;编译时异常必须要进行try-catch处理。
public class Main{
public static void main(String[] args){
try{
test(1,0);
} catch(Exception e){
e.printStackTrace();//打印栈追踪信息
System.out.println("异常错误信息:"+e.getMessage());//获取异常的错误信息
}
}
// 抛到main函数中去,由main函数来解决
private static int test(int a,int b) throws Exception{
if(b==0) throw new Exception("除数不能为0");
return a/b;
}
}
-
finally关键字:
使用方法:可以try-catch-finally运用或try-finally运用
作用:finally中的语句无论什么时刻都会执行,就算有异常的出现。