异常
异常:程序员可以进行处理的意外(Exception)
运行期异常:只有程序运行起来时,才能验证是否有异常
ArithmeticException 除数为0
ArrayIndexOutOfBoundsException 数组越界
NullPointerException 引用数据类型的对象在使用前没有对其赋值
编译器异常:在编译期就需要处理的异常
直接抛出Exception
异常分类——
运行期异常:非首检异常
所有的RuntimeException类型的子类 都是运行期异常。发生频繁,易控制。
编译期异常:受检异常
Exception的直接子类。
当程序出现异常时,为了不让程序停止下来
1.try-catch进行捕捉异常,
try{ Person p =null;// System.out.println(p.name); System.out.println(p.age); }catch (NullPointerException e){ System.out.println("出现异常,没给对象赋值。"); e.printStackTrace();//打印错误信息 开发中一定要输出 }
对异常进行捕捉:
}catch (NullPointerException e){ System.out.println("出现异常,没给对象赋值。"); e.printStackTrace();//打印错误信息 开发中一定要输出 }catch (ArithmeticException e){ System.out.println("异常,除数为0。"); e.printStackTrace(); }catch (ArrayIndexOutOfBoundsException e){ System.out.println("数组越界。"); e.printStackTrace(); }
只有发生异常时,才能去执行cath,匹配了就会停止在cath不会继续执行,如果全部没有匹配则相当与没有处理。
多cath时:
-
try不可以单独存在
-
可以同时存在多个cath,如果cath间存在子父类的关系,那么需要先抓取子再抓父。
-
不管是否存在异常,finally必须放在try的最后,切finally的代码必须执行(清理行工作)
出现return也会执行,除非遇到System.exit(0)。虚拟机关闭
2.throws 扔出去 在方法上扔
public class Text02 {
public int device(int x,int y) throws ArrayIndexOutOfBoundsException{
int s=0;
s = x/y;
System.out.println("在方法中的值是:"+s);
System.out.println("程序继续执行。");
return s;
}
public static void main(String[] args) {
Text02 t = new Text02();
int s =0;
try {
s = t.device(10,0);
}catch (ArithmeticException e){
e.fillInStackTrace();
}
System.out.println("执行后的结果是:"+s);
System.out.println("1。");
System.out.println("2。");
System.out.println("3。");
}
}
throws抛出异常,通过ArithmeticException抓住异常,执行e.fillInStackTrace();
后续依次向下执行。