一、异常的类型:
1. Error:没法改变的错误
2. Exception:可以改变的错误
二、程序中的常见异常:
1. ArithmeticExecption 异常-数字运算异常
2. NullPointerExecption 异常-空指针异常
3. NegativeArraySizeExecption 异常-数值大小为负值异常
4. NumberFormatExecption 异常-数字格式异常
5. InputMismatchExecption 异常-输入类型不匹配异常
6. NoSuchMethodExecption 异常-方法不存在异常
7. DataFormatExecption 异常-数据格式错误异常
8. NoClassDefFoundError 错误-未找到类定义错误
三、异常举例:
(1)int a = 3 / 0;// 1. ArithmeticExecption 异常-数字运算异常
(2)String s=null;
s.charAt(0);//2. NullPointerExecption 异常-空指针异常
(3)int b[]=new int[-7];//3. NegativeArraySizeExecption 异常-数值大小为负值异常
(4)int c[]=new int[1];
c[1]=9;//ArrayIndeOutOfBoundsException
(5)String s="32,4";
double d=Double.valueOf(s);//4. NumberFormatExecption 异常-数字格式异常
(6) Scanner sc=new Scanner(System.in);
int e=sc.nextInt();//6. InputMismatchExecption 异常-输入类型不匹配异常
(7) A a1=new A();//父类
B b1=new B();//子类
b1=(B)a1;//父类转换成子类 强制类型转换 会报错 7.ClassCastException-类转换异常
(8) A a2=new B();
b1=(B) a2;//向下转型 可以成功8. DataFormatExecption 异常-数据格式错误异常
}
class A{
}
class B extends A{
}
四、异常处理
1. try-catch-finally 处理异常
package test4;
import java.util.Scanner;
//异常捕获处理异常
public class test2 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int b=sc.nextInt();try {//可能发生异常语句
int a=3/b;//一旦发生异常,后面语句不会执行
System.out.println("test1");
}catch(ArithmeticException e) {
System.out.println("除数不能为 0");
}finally {
System.out.println("test2");
}
System.out.println("test3");
}
}
2. throw 抛出异常
语法格式:throw 异常类对象;
在 throw 语句后立刻终止
(不常用,需最终解决)
四、补充:
1. 多 catch 代码块
如果 try 代码块中有很多语句会发生异常,且异常种类不止一种,try 后面可以跟
多个 catch 代码块。
格式:
Try{
}catch(Throwable e){ }
catch(Throwable e){ }//以此类推
(1) 当一个 catch 代码块捕获一个异常时,其他 catch 代码块不再进行匹配
(2) 当 catch 代码块存在父类和子类异常,先捕获子类异常,再捕获父类异常。
package test4;
import java.util.InputMismatchException;
import java.util.Scanner;
public class test4 {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
try {
int flag=sc.nextInt();
int b=3/flag;
int c[]=new int[flag];
c[1]=4;
String s=null;
s.charAt(flag);
}catch(InputMismatchException e) {
System.out.println("输入不是整型");
}catch(ArithmeticException e) {
System.out.println("除数不能为0");
}catch(NegativeArraySizeException e) {
System.out.println("不能是负数");
}
//或者换成多个 catch(InputMismatchException/ArithmeticException e){
//System.out.println("输入数据不正确");
//}
}
}
2. 多重捕获
异常种类不同,但处理相同时
格式:
Try{ }catch(AExceptiopn|BException){//这里的 A、B 指不同类型错误
//调用方法处理}