(1)基本概念
1.1、异常就是“不正常”的含义,在java语言中主要是指程序执行中发生的不正常情况。
1.2、Java.Lang.Throwable类就是Java语言中错误(Error)和异常(Exception)的错误。
1.3、其中Error类主要用于描述Java虚拟机无法解决的严重错误,通常无法通过编码解决,比如:JVM挂掉了等。
1.4、其中Exception类主要用于描述因编程错误或偶然外在因素导致的轻微错误,通常可以编码解决,如:0作为除数等。
(2)异常的分类
Java.lang.Exception类是所有异常的超类,主要分为以下两种:
其中RuntimeException类的主要子类:
示例代码
非检测异常-运行时异常:编译ok,运行阶段会发生算术异常 下面的代码不会执行
System.out.println(5/0);
System.out.println("程序正常结束!!!");
运行结果:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at day02_BigInteger.ExceptionTest.main(ExceptionTest.java:9)
检测异常
Thread.sleep(1000);//编译错误
运行结果:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type InterruptedException
at day02_BigInteger.ExceptionTest.main(ExceptionTest.java:9)
(3)异常的避免
常见异常代码示例:(如果代码能够正常运行,最终的运行结果将会输出正常运行的字样,如果碰到异常代码的运行将会停止第一次出现异常的地方。)
//算术异常
int ia=10;
int ib=0;
System.out.println(ia/ib);
//数组下标越界异常
int[]arr=new int[5];
int pos=5;
System.out.println(arr[pos]);
//空指针异常
String str=null;
System.out.println(str.length());
//类型转换异常
Exception ex=new Exception();
IOException ie =(IOException)ex;
//数字格式异常
String str2="123a";
System.out.println(Integer.parseInt(str2));
System.out.println("程序就正常结束了!!!");
运行结果:(程序停止在第一个算术异常的地方停止!)
Exception in thread "main" java.lang.ArithmeticException: / by zero
at day02_BigInteger.ExceptionPreventTest.main(ExceptionPreventTest.java:11)
异常的避免,这里使用if语句做条件判断,对异常进行避免。添加if语句后的代码如下:
//算术异常
int ia=10;
int ib=0;
if(0!=ib) {
System.out.println(ia/ib);
}
//数组下标越界异常
int[]arr=new int[5];
int pos=5;
if(pos>=0 && pos<5) {
System.out.println(arr[pos]);
}
//空指针异常
String str=null;
if (null!=str) {
System.out.println(str.length());
}
//类型转换异常
Exception ex=new Exception();
if (ex instanceof IOException) {
IOException ie =(IOException)ex;
}
//数字格式异常
String str2="123a";
//涉及正则表达式(后续会学习更新的!!)
if (str2.matches("\\d+")) {
System.out.println(Integer.parseInt(str2));
}
System.out.println("程序就正常结束了!!!");
运行结果:程序就正常结束了!!!
通过简单的if语句就可以对异常进行避免,但是我们会发现 if语句虽然有用,但是如果过多的使用,它会显示出代码加长,显得臃肿,可读性变差。
【好了~今天就先到记录到这里了~,非常高兴收到星星的晚安~,晚安喽~~~】