本章内容
RuntimeException异常处理
CheckedException异常处理
RuntimeException异常处理
特点:
-
产生频繁---数组下标越界、空指针等等
-
显式声明或捕捉对程序可读性和运行效率影响较大
-
由系统自动检测并将它们交给缺省的异常处理程序
成因:
-
由编程错误导致
处理办法:
-
不要求必须使用异常处理机制
-
通过增加"逻辑处理"来避免这些异常---解决运行时异常的思路:---增加判断
举例:
public class Test3{
public static void main(String[] args){
int b = 0;
System.out.println(1/b);
}
}
修改:
public class Test3{
public static void main(String[] args){
int b = 0;
if(b != 0){
System.out.println(1/b);
}
}
}
NullPointerException异常---空指针
调用空对象的方法:
public class Test3{
public static void main(String[] args){
String str = null;
if(str != null){
System.out.println(str.length());
}
}
特点:
-
引文str对象为空,里面没有方法
-
所以抛出异常
-
加判断
ClassCastException异常---引用数据类型转换时的类型转换异常
实例:
package com.exception;
/**
* 测试异常处理
* @author Lucifer
*/
public class Test01 {
public static void main(String[] args) {
int a = 0;
if (a != 0){
System.out.println(1/a);
}else {
System.out.println("Wrong");
}
//空指针
String str = null;
if (str != null){
System.out.println(str.length());
}
/*新建Animal对象然后强制转型成继承Animal的子类对象*/
Animal d = new Dog();
//强制转对象的类型
if (d instanceof Cat){
Cat c = (Cat) d;
}
//同样继承Animal,子类之间不能互相强制转型
}
}
/*建Animal类*/
class Animal{
}
/*写一个Dog类继承Animal*/
class Dog extends Animal{
}
/*写一个猫类继承Animal*/
class Cat extends Animal{
}
ArrayIndexOutOfBoundsException异常---索引超出数组索引长度抛出的下标越界异常
public class Test6{
public static void mai(String[] args){
int[] arr = new int[5];
if(a < arr.length){
System.out.println(arr[5]);
}
/*
越界了,加判断
*/
}
}
NumberFormatException异常---在使用包装类将字符串转换成基本数据类型时候因为字符串格式不正确抛出的异常
public class Test7{
public static void main(String[] args){
String str = "1234abcf"; //因为由abcf所以会抛出异常,先判断---用正则表达式去匹配判断
Pattern p = Pattern.compile("^\\d + $");
Matcher m = p.matcher(str);
if(m.matches()){
//如果str匹配代表数字的正则表达式,才会转换
System.out.println(Intergrer.paraseInt(str));
}
}
}
这些异常都是需要去检查或者是去处理的