![cover](https://img-blog.csdnimg.cn/direct/dc3f3a1885a04e5dbed57881f143898a.png)
Exception异常处理---常用异常类
Exception表示运行期间,由于各种客观原因导致的运行错误。Exception又分为两大类:RuntimeException和检查异常。
·
一、异常框架
二、Error
Error表示严重的错误,程序一般无能为力,例如:
1.内存溢出:OutOfMemoryError
//内存溢出:OutOfMemoryError
//内存申请大容量空间时,内存不够
byte[] arr1=new byte[2147483647];
byte[] arr2=new byte[2147483647];
byte[] arr3=new byte[2147483647];
2.堆栈溢出:StackOverflowError
private static void dosth() {
//无限层次的递归
dosth();
}
三、Exception
Exception表示运行期间,由于各种客观原因导致的运行错误。Exception又分为两大类:RuntimeException和检查异常。
Java规定:
①必须要捕获的异常,包括Exception及其子类,但不包括RuntimeException及其子类,这种异常叫做Checked Exception(检查异常)。
②不需要捕获的异常,包括Error及其子类,RuntimeException及其子类。
1.运行异常:RuntimeException
例如:
(1)输入内容不匹配异常:InputMismatchException
try (Scanner input = new Scanner(System.in)) {
//1.获取输入时,可能出现InputMismatchException
int n1=input.nextInt();//输入a
int n2=input.nextInt();
}
(2)算术逻辑异常:ArithmeticException
try (Scanner input = new Scanner(System.in)) {
int n1=input.nextInt();
int n2=input.nextInt();
//2.计算除法时,可能产生ArithmeticException
System.out.printf("%d÷%d=%d",n1,n2,n1/n2);//除数为0
}
(3)数组下标越界异常:ArrayIndexOutOfBoundsException
//3.由于超出范围,产生数组下标越界ArrayIndexOutOfBoundsException
int[] ns= {11,23,44,67};
System.out.println(ns[99]);
(4)字符串下标越界异常:StringIndexOutOfBoundsException
//4.由于超出范围,产生字符串下标越界StringIndexOutOfBoundsException
String s="但使龙城飞将在";
System.out.println(s.charAt(99));
(5)空指针异常:NullPointerException
//试图访问一个为Null的对象时,会产生NullPointerException
String s=null;
System.out.println(s.trim());
int[] ns=null;
//试图访问一个为Null的数组时,会产生空指针异常:NullPointerException
System.out.println(ns.length);
(6)格式化异常:NumberFormatException
//4.格式化异常:NumberFormatException
String s="23s";
int n=Integer.parseInt(s);
System.out.println(n*10);
(7)IllegalFormatFlagsException
String str =String.format("%(%d)", 11,12);
System.out.println(str);
2.检查异常(编译器异常)
所有需要捕获的异常都是检查异常,非RuntimeException的异常都是检查异常。
更多推荐
所有评论(0)