-
异常指程序运行中出现的不期而至的各种状况,如:文件找不到,非法参数,网络连接失败等。异常发生在程序运行器件,它影响了正常程序的执行流程。
-
异常处理机制(抛出异常和捕获异常):异常处理五个关键字try、catch、finally、throw、throws
public class Text {
public static void main(String[] args) {
int a=1;
int b=0;
try {
//try监控区域
System.out.println(a/b);
}catch (Error e){
//catch(想要捕获的异常类型)
System.out.println("程序出现异常,Error");
}catch (Exception x){
System.out.println("程序出现异常,Exception"); //Exception和Throwable交换顺序会报错,Throwableji要大一些
}catch (Throwable t){
System.out.println("程序出现异常,Throwable");
}
finally {
//处理善后工作,无论出不出异常,finally都会执行
System.out.println("finally");
}
}
public void a(){
b();
}
public void b(){
a();
}
}
/*输出:
程序出现异常,Exception
finally
Process finished with exit code 0
*/
======================================================
public class Tex1 {
public static void main(String[] args) {
try{
new Tex1().text(1,0);}
catch (ArithmeticException e){
e.printStackTrace();
}
}
//假设这个方法中,处理不了这个异常,方法上主动抛出异常
public void text(int a,int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException();//主动抛出异常,一般在方法中使用
}
System.out.println(a/b);
}
}
- 自定义异常
//此处两个class文件
//自定义异常类,只需要继承Exception类
public class Text extends Exception{
//传递数字>10
private int detail1;
public Text(int a){
this.detail1=a;
}
//toString 打印信息的方法 //异常的打印信息
@Override
public String toString() {
return "Text{" + "detail1=" + detail1 + '}';
}
}
public class Tex1 {
public static void main(String[] args) {
try{
test(11);
}catch (Text e){
System.out.println("自定义的异常"+e);
}
}
//可能会存在异常的方法
static void test(int a) throws Text{
if(a>10){
throw new Text(a); //抛出
}
System.out.println("OK");
}
}
/*输出:
自定义的异常Text{detail1=11}
Process finished with exit code 0
*/
- 经验总结
- 处理运行时异常时,采用逻辑去合理规避同时辅助try-catch处理
- 在多重catch块后面,可以加一个catch(Exception)来处理可能会被遗漏的异常
- 对于不确定的代码,也可以加上try-catch,处理潜在的异常
- 尽量去处理异常,切忌只是简单的调用printStackTrace()去打印输出
- 具体如何处理异常,要根据不同的业务需求和异常类型去决定
- 尽量添加finally语句块去释放占用的资源。