异常Exception
异常指的是程序在执行过程中,出现的非正常情况,最终会导致JVM的非正常停止。在java等编程语言中,异常本身就是一个类,产生异常就是创建了一个异常对象并抛出这个异常。Java处理异常的方式是中断处理。
异常的根类是Throwable,其下有两个子类,Error与Exception。Exception有一个子类RuntimeException。Exception是程序开发过程中可以解决的问题,而Error是只能尽力去避免的问题。
异常的产生原理:
处理异常的几个关键字:throw、throws、try…catch、finally
其用法如下:
1.throw:使用throw关键字在指定的地方抛出指定的异常
注意:
1.throw关键字必须写在方法内部
2.throw关键字后边new的对象必须为Exception或其子类
3.throw关键字抛出指定的异常对象,我们就必须处理这个异常对象
a.方法1:如果是runtimeException或其子类异常,可以交给JVM处理(打印异常对象,中断程序)
b. 方法2:如果是编译异常,自己处理,要么throws,要么try…catch
在工作中,我们必须对传递的参数进行合法性校验,
如果参数不合法,必须使用抛出异常的方式,告知方法的调用者,传递的参数有问题
public static void main(String[] args) {
int[] arr = {1,2,3};
getArr(arr,3);
}
public static int getArr(int[] arr,int index){
if (arr == null) {
throw new NullPointerException("空指针异常");
}
if (index< 0 || index >arr.length - 1) {
throw new ArrayIndexOutOfBoundsException("数组索引越界异常");
}
return arr[index];
}
另Object类有检查是否为空指针的方法Objects.requireNonNull();
public static void nethod(Object obj) {
if (obj == null) {//为空打印输出"空指针"
Objects.requireNonNull(obj, "空指针");
}
}
2.throws把异常交给别人处理:
作用:
当方法内部抛出异常对象的时候,我们就必须处理这个异常对象。
throws会把异常对象声明抛出给方法的调用者处理,最终交给JVM处理->中断处理
注意:
1.throws关键字必须写在方法声明处
2.throws关键字后面声明的异常必须是Exception或其子类。
3.方法内部如果抛出了多个异常对象,那么throws后边必须也声明多个异常
4.如果抛出多个异常对象有子父类关系,那么直接声明父类即可。
//抛出异常的写法
//public static void main(String[] args) throws FileNotFoundException,IOException{
//FileNotFoundException extends IOException extends Exception
//public static void main(String[] args) throws IOException{
public static void main(String[] args) throws Exception{
readFile("c\\a.txt");
}
public static void readFile(String fileName)
throws FileNotFoundException,IOException {
//检查前缀
if (!fileName.startsWith("c\\a")) {
throw new FileNotFoundException("文件路径不对");
}
//检查后缀
if (!fileName.endsWith(".txt")) {
throw new IOException("文件后缀名不对");
}
System.out.println("正确");
}
3.try…catch…finally:处理异常的第二种方式
注意:
1.try中可能抛出多个异常对象,那么就可以使用多个catch来处理这些异常对象
2.如果try中产生了异常,那么就会执行catch中的异常处理逻辑, 执行完毕catch后,继续执行try…catch之后的代码
如果try中没有产生异常,那么就不会执行catch中的异常处理逻辑,直接执行try…catch之后的代码
3.finally不论是否抛出异常都会执行
注意:1.finally不能单独使用,必须和try…catch结合。2.finally一般用于资源释放(IO)
public static void main(String[] args) {
try {
//可能出错的代码
readFile("d\\a.txt");
}catch (FileNotFoundException e){//抛出什么异常,就定义什么异常
//System.out.println("名不对");
/*
Throwable中定义了三个异常处理的方法
String getMessage()返回此throwable的简短信息
String toString()返回此throwable的详细信息
void printStackTrace()JVM打印最全面的信息
* */
System.out.println(e.getMessage());
System.out.println(e.toString());
e.printStackTrace();
}catch (IOException e){
System.out.println("后缀错啦");
}//finally不论是否抛出异常都会执行
// 注意:1.不能单独使用,必须和try..catch结合。2.finally一般用于资源释放(IO)
finally {
//避免在finally中写return
System.out.println("资源释放");
}
System.out.println("后续代码");
}
public static void readFile(String fileName)
throws FileNotFoundException, IOException {
//检查前缀
if (!fileName.startsWith("c\\a")) {
throw new FileNotFoundException("文件路径不对");
}
//检查后缀
if (!fileName.endsWith(".txt")) {
throw new IOException("文件后缀名不对");
}
System.out.println("正确");
}