异常:异常就是代表程序出现的问题。
异常体系
Error:
代表的系统级别错误(属于严重问题),系统一旦出现问题,sun公司会把这些错误封装成Error对象,Error是给sun公司自己用的,不是给我们程序员用的。因此我们开发人员一般不用管它。
Exception:
叫做异常,代表程序可能出现的问题。我们通常用Exception以及它的其他子类来封装程序出现的问题。
运行时异常:
RuntimeException及其子类,编译阶段不会出现异常提醒,而是在运行时出现的异常,一般是由于参数传递错误,或者是代码写错了。(如:数组索引越界异常 ArrayIndexOutOfBoundsException)
编译时异常:
编译阶段就会出现的异常提醒,作用在于提醒程序员。(如:日期解析异常)
异常的作用
作用一: 异常是用来查询bug的关键参考信息。
作用二: 异常可以作为方法内部的一种特殊返回值,以便通知底层调用者的执行情况。
异常的处理方式
JVM默认的处理方式:
1.把异常的名称,异常的原因以及异常出现的位置等形象输出在控制台。
2.程序停止执行,异常以下的代码不会执行。
自己处理(捕获异常):
1.格式:
try {
可能出现异常的代码
} catch (异常类名 变量名) {
异常的处理代码
}
2.目的:
当代码出现异常时,可以让程序往下执行。
int[] arr = {1, 2, 3, 4};
try {
System.out.println(arr[4]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界了");
}
System.out.println("我执行了吗");
3.自己处理(捕获异常)的三个注意:
一、如果try中没有遇到问题,则会把try里面所有代码全部执行完毕,不会执行catch里面的代码。只有当出现了异常才会执行catch里的代码。
二、如果try中遇到多个问题,则我们要写多个catch与之对应。在捕获这多个异常时,这些异常如果存在父子关系的话,则父类异常一定要写到下面。
三、如果try中遇到了问题,则会直接跳转的catch中,执行catch里面的语句体,而try中后续代码则不会执行。
Throwable的成员方法
int[] arr = {1, 2, 3, 4, 5};
try {
System.out.println(arr[6]);
} catch (ArrayIndexOutOfBoundsException e) {
/*
String message = e.getMessage();
System.out.println(message);
String string = e.toString();
System.out.println(string);
*/
e.printStackTrace(); //无返回值,仅仅是打印信息(包含的信息最多),不会停止程序运行
//在底层是利用System.arr.println进行输出,把异常错误以红色字体输出到控制台
抛出处理
public static void main(String[] args) {
int[] arr = null;
int res = 0;
try {
res = getMax(arr); //可能出现问题的代码
} catch (NullPointerException e) { //捕获异常
e.printStackTrace();
} catch (ArithmeticException e) { //捕获异常
e.printStackTrace();
}
System.out.println(res);
}
//设置一个求数组中最大值的方法
private static int getMax(int[] arr) throws NullPointerException,ArithmeticException{ //throws提醒调用者,本方法可能有哪些异常
if (arr == null) { //可能出现空指针异常
throw new NullPointerException(); //手动抛出这个异常
}
if(arr.length == 0) {
throw new ArithmeticException(); //手动抛出可能出现的算数异常
}
int max = arr[0];
for (int i = 1; i< arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
自定义异常
public class NameFormatException extends RuntimeException{
//运行时:RuntimeException 表示参数错误
//编译时:Exception 提醒程序源检测本地信息
public NameFormatException() { //无参方法和有参方法 可以Alt + Insert 一键生产
}
public NameFormatException(String message) {
super(message);
}
}