异常的背景
认识异常
异常
就是程序在运行时出现错误通知调用者的一种机制(编译出错不属于此处的异常)
例如(除0异常)
System.out.println(10 / 0);
// 执行结果
Exception in thread "main" java.lang.ArithmeticException: / by zero
防御式编程
避免异常的两种方式
异常的基本语法
1.使用try catch处理异常
public static void main(String[] args) {
// System.out.println(10/0);
int arr[]={1,2,3};
try {
//存放可能发生异常的代码块
System.out.println(arr[4]);
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println("数组下标越界");
}
finally {
System.out.println("hello");
}
//运行结果
//数组下标越界
//hello
}
2.多个catch块
3.使用异常的共同父类Exception来捕获异常
4.finally代码块
finally
无论是否产生异常,都会执行的代码块
public static void main(String[] args) {
// System.out.println(10/0);
int arr[] = {1, 2, 3};
try {
arr = null;
//存放可能发生异常的代码块
System.out.println(arr[4]);
}
catch (Exception e){
System.out.println("异常出现");
}
finally {
System.out.println("hello");
}
}
//运行结果
//空指针异常
//hello
5.异常返回值
6.throw和throws
throws
:用在方法声明上,明确表示该方法有可能会产生异常,但是不处理,抛回给调用者
throw
:用在方法内部,认为产生异常对象并抛出
异常体系结构
1.顶层类 Throwable 派生出两个重要的子类,
Error
和Exception
2.其中 Error 指的是 Java 运行时内部错误和资源耗尽错误. 应用程序不抛出此类异常. 这种内部错误一旦出现,
除了告知用户并使程序终止之外, 再无能无力. 这种情况很少出现.
3.Exception 是我们程序猿所使用的异常类的父类.
4.其中 Exception 有一个子类称为RuntimeException
, 这里面又派生出很多我们常见的异常类
NullPointerException , IndexOutOfBoundsException 等.
异常体系分类
自定义异常
程序开发中,一定有些错误是和具体业务相关的,这种时候JDK不可能提供相应的异常类,此时我们就需要继承已有的异常类,产生自定义异常。