1 - 异常
1.1 - 基本概念
异常,指不正常,在Java中异常处理能让程序在异常发生的情况时,按照事先设定好的处理方式去有针对性的做处理。
java.lang.Throwable类是Java中所有错误和异常的超类,已知直接子类有:Error类和Exception类、
1.2 - 异常的主要分类
名称 | 说明 |
---|---|
RuntimeException | 运行时异常类,也叫作非检测性异常 |
IOException | IO异常类,也叫作检测性异常 |
RuntimException类的主要子类
异常类型 | 说明 |
---|---|
ArithmeticException | 算数异常 |
ArrayIndexOutofBoundsException | 数组下标越界异常 |
NullPointerException | 空指针异常 |
ClassCastException | 类型转换异常 |
NumberFormatException | 数组格式异常 |
运行时异常的处理方式
绝大多数的运行时异常/非检测性异常都可以通过if()条件判断的形式避免发生
import java.io.IOException;
/**
* @author ly_smith
* @Description #TODO 运行时异常的主要分类
*/
public class Demo06 {
public static void main(String[] args) {
int a = 10;
int b = 0;
if(b != 0){
System.out.println(a/b);//算数异常ArithmeticException
}
int[] arr = new int[5];
int post = 5;
if(post >= 0 && post < 5){
System.out.println(arr[post]);//java.lang.ArrayIndexOutOfBoundsException
}
String s1 = null;
if (s1 != null){
System.out.println(s1.length());//java.lang.NullPointerException
}
Exception e = new Exception();
if(e instanceof IOException){
IOException io = (IOException) e;//java.lang.ClassCastException
}
String s2 = "123abc";
if(s2.matches("\\d+")){
System.out.println(Integer.parseInt(s2));//NumberFormatException
}
}
}