异常处理
程序执行中发生不正常的情况
Error
java虚拟机无法解决的严重问题
常见的编译异常
SQLException
操作数据库时,查询表可能发生的异常
IOException
操作文件时,发生异常
FileNotFoundException
操作不存在文件时,发生异常
ClassNotFoundException
加载不存在类,发生异常
EOFException
操作文件到末尾。发生异常
IIegalArguementException
参数异常
Exception
编程错误或偶然的外在因素的一般性错误。又分为运行时异常,编译异常。
常见的五个异常
空指针异常
当应用程序试图在需要对象的地方使用null时,抛出该异常。
public class NullPointerException {
public static void main(String[] args) {
String name =null;
System.out.println(name.length());
}
}
算术异常
除于0
数组越界
下标索引大于数组长度。
public class NullPointerException {
public static void main(String[] args) {
int[] name = {1,2,3};
System.out.println(name[3]);
}
}
类型转换异常
试图将对象强制转换为不是实例的子类时,抛出异常
数字格式不正确异常
试图将字符串转换成一种数值类型,但该字符串不能转换为适当格式时,抛出异常,可以确保输入的是满足条件的数字。
异常处理
如果不显示的处理异常,默认是throws。
try-catch-finally
- ctrl+alt+t
- 如果代码块有多个异常,可以通过捕获不同的异常处理,子异常必须在父异常之上,
- try-finally,不捕获异常,直接崩掉,应用场景:不管发布发生异常,都必须执行某个业务逻辑
public class Exception01 {
public static void main(String[] args) {
int num2=0;
int mun1=10;
// 抛出异常,但不停止程序。
try {
int res = mun1/num2;
}catch (Exception e){//异常封装成Exception对象e,传递给catch.
e.printStackTrace();
}finally{
//不管有没有异常出现都会执行finally代码块
}
System.out.println("xxx");
}
}
/*
捕获多个异常
*/
try{
}catch(子异常){
}catch(父异常){
}finally{
}
throws
将异常抛给上级。方法n->方法n1->main->JVM

public class NullPointerException {
public static void main(String[] args) {
}
public static void f1() throws Exception{
//编译异常
// try-catch-finally方法
// throws抛出异常,让调用此方法的调用者(方法)处理
// throws 异常可以是他的父类
// throws 后面也可以是一个数组,抛出多个异常
new FileInputStream("D:xxxxx.txt");
}
}
注意事项和使用细节
- 编译异常,程序必须处理
- 运行时异常,默认是throws方式处理
- 子类重写父类方法时,对抛出的异常规定:子类重写的方法,所抛出的异常类型要么和父类抛出的异常一致。要么为父类抛出异常的类型的子类型
- throws过程中,如果有方法try-catch,就相当于处理异常,就可以不必throws.
自定义异常
-
定义类,继承Exception或者RuntimeException
-
继承Exception属于编译异常
-
继承RuntimeException属于运行异常,一般继承RuntimeException
public class CustomException01 { public static void main(String[] args) { int age = 120; if (!(age>=18&&age<=100)){ throw new AgeException("年龄需要在18-10之间") } System.out.println("你的年龄范围正常"); } } class AgeException extends RuntimeException{ public AgeException(String message){ super(message); } }