1.异常体系图
NullaPointException空指针异常
ArrayIndexOutofBoundsException数组索引越界异常
ClassCastException类型转换异常
NumberFormatException数字格式异常
ArithmeticExecption算术异常
常见的编译时异常
编译异常必须处理
2.异常处理方式
1.try...catch...finally
快捷键:alt+ctrl+t,选择try..catch
(1).多个异常可以使用多个catch分别捕获不同的异常,进行处理;要求子类异常要写在前面,父类异常写在后面
(2).可以使用try—finally,没有捕获异常,不管发生什么都执行finally;有异常执行完finally直接崩了,不继续执行了
public class TryCatchDetail {
public static void main(String[] args) {
try {
String str="你好";
int a=Integer.parseInt(str);
System.out.println(a);
} catch (NumberFormatException e) {
//有异常捕获异常,进行处理
//没有异常,跳过
System.out.println(e.getMessage());
} finally {
//不管有没有异常都执行
System.out.println("关闭一些资源,连接");
}
//有异常:异常处理完继续执行下面的
//没有异常直接执行下面的
System.out.println("程序继续");
}
}
练习:
执行return ++i时,i=3,但是还要继续执行finally,所以先把i=3保存到临时变量中
finnlly里面输出i=4,再返回去执行return 3;
练习:
public class Try02 {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
boolean b=true;
while (true){
System.out.println("请输入一个整数");
String s=sc.next();
try {
int num= Integer.parseInt(s);
System.out.println("正确");
break;
} catch (Exception e) {
System.out.println("你输入的不是一个整数");
}
}
}
}
2.throws
每一级可以选择try-catch或往上一级抛
1.如果一个方法可能生成某种异常,但是并不能确定如何处理这种异常,则该方法应显示的声明抛出异常,表明该方法将不对这些异常处理,而由该方法的调用者负责处理。
2.在方法声明中用throw语句可以抛出异常的列表
细节:
(1).底层抛出的异常必须是上级的子类
3.编译时异常和运行时异常
1.编译异常必须处理
2.对于运行异常如果没有处理,默认是throws
public class throws_ {
public static void main(String[] args) {//这也默认throws ArithmeticException
f2();
}
public static void f2(){//这默认throws ArithmeticException
//1.运行时异常,如果程序没有处理,默认就是throws
int n1=10;
int n2=0;
double r=n1/n2;
}
}
3.子类重写父类的方法时,对抛出异常的规定:子类重写的方法,所抛出的异常类型要么和父类抛出的异常一致,要么为父类抛出的异常类型的子类型
4.自定义异常
1.一般继承运行时异常runtimeException
2.好处是,可以使用运行时异常的默认处理机制
3.练习
public class a {
public static void main(String[] args) {
int age=10;
if(!(age>=18 && age<=120)){
throw new AgeException("年龄需要在18-120");
//throw 后面是一个异常对象
//throws 是抛出一个异常
//不一样的
}
}
}
//自定义一个类
//1.一般情况自定义异常是继承RuntimeException
//2.好处是,我们可以使用默认的处理机制
class AgeException extends RuntimeException{
public AgeException(String message) {
super(message);
}
}
5.练习
(1).输出什么
(2).
public class c {
public static void main(String[] args) {
//先验证输入的参数的个数
try {
if (args.length!=2){
throw new ArrayIndexOutOfBoundsException("参数个数不对");
}
int n1=Integer.parseInt(args[0]);
int n2=Integer.parseInt(args[1]);
double res=cal(n1,n2);//该方法可能抛出ArithmetExecption
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}catch (NumberFormatException e){
System.out.println("参数格式不正确");
}catch (ArithmeticException e){
System.out.println("不能除以0");
}
}
public static double cal(int n1,int n2){
return n1/n2;
}
}
(3).