将程序执行中发生的不正常情况称为 异常{有 1.Error 2.Exception 两种}
Error
- Error:Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等严重情况,像
StackOverflowError[栈溢出]、OOM[out of memory],Error是严重错误,程序会崩溃
Exception
- Exception:其它因编译错误或偶然的外在因素导致的一般性问题,可以使用针对性代码进行处理。
如:空指针访问、试图读取不存在的文件、网络连接中断等等
注: 在Exception也分两大类:运行时异常 、 编译时异常;对于Error 这种严重问题我们无法通过代码解决,但Exception,我们可以通过异常处理机制来解决。
- 我们可以通过try-catch异常处理机制来解决,idea中(选中异常代码块-> 快捷键ctrl+alt+t -> 选中try-catch)
- try-catch就是把抛出异常代码块放在try语句中,异常放在catch语句,如果try语句中没有异常抛出,则不执行catch语句,通过这种处理就算出现异常,程序也可以继续执行,不会直接导致程序崩溃。
public class TE {
public static void main(String[] args) {
int a = 10;
int b = 0;
try {
int c = a/b;
} catch (Exception e) {
//e.printStackTrace();
System.out.println("原因:" + e.getMessage());
}
System.out.println("虽说有异常,但继续执行...");
}
}
try-catch处理机制需要注意
- try-catch如果异常发生则进入catch语句;没有发生异常则不执行catch语句
- catch语句可以有多个,但异常必须先写子类在写父类
public class DivisionMethodException {
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]);
division(n1, n2);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
} catch (NumberFormatException e) {
System.out.println("参数格式不对");
} catch (ArithmeticException e) {
System.out.println("除0 错误");
}
}
public static void division(int n1, int n2) {
System.out.println("计算结果=" + (n1 / n2));
}
}
- catch后面可以跟finally,finally与异常无关,写了就会执行
- try中异常发生后try后面未执行语句不再执行,直接进行catch和finally
public class TE {
public static void main(String[] args) {
int a = 10;
int b = 2;
try {
int c = a/b;
} catch (Exception e) {
//e.printStackTrace();
System.out.println("原因:" + e.getMessage());
} finally {
System.out.println("写了就执行...");
}
}
}
变量b不为0时,程序没有执行catch,但finally 执行了
像除0这种异常就是运行异常中的 ArithmeticException,编译时不会报错但运行报错
常见的运行异常:
- NullPointerException 空指针异常
- ArithmeticException 数学运算异常
- ArrayIndexOutOfBoundsException 数组下标越界异常
- ClassCastRxception 类型转换异常 对象转换成不是实例的子类
- NumberFormatException 数字格式不正确异常 String转int
编译异常在编译时就不会通过
常见的编译异常:
- SQLException 操作数据库时,查询表可能发生异常
- IOException 操作文件时,发生的异常
- FileNotFoundException 当操作一个不存在的文件时,发生异常
- ClassNotFoundException 加载类,而该类不存在时,异常
- EOFException 操作文件,到文件末尾,发生异常
- IllegalArguementException 参数异常
异常也有继承关系:
这里没有细分
自定义异常
1. 自己定义一个异常类,继承Exception或RuntimeException
2. 自定义异常类;继承Exception属于编译异常,继承RuntimeException属于运行异常
3. 一般继承RuntimeException运行异常,可以用默认处理机制
注: 在jbk5以后运行异常有默认处理机制:throws ,它的处理很简单,就是把异常抛出去,最后抛给JVM机,它会直接输出异常然后崩掉程序(现在运行报错就是这种)