1 概述

Java中的异常全面讲解_Java开发
Java定义了一个异常类的层次结构,其以Throwable开始,扩展出Error和Exception,而Exception又扩展出RuntimeException.

2 java中的异常处理

在Java中如果需要处理异常,必须先对异常进行捕获,然后再对异常情况进行处理。如何对可能发生异常的代码进行异常捕获和处理呢?使用try和catch关键字即可,如下面一段代码所示:

try {
  File file = new File("d:/a.txt");
  if(!file.exists())
    file.createNewFile();
} catch (IOException e) {
  // TODO: handle exception
}

被try块包围的代码说明这段代码可能会发生异常,一旦发生异常,异常便会被catch捕获到,然后需要在catch块中进行异常处理。

这是一种处理异常的方式。在Java中还提供了另一种异常处理方式即抛出异常,顾名思义,也就是说一旦发生异常,我把这个异常抛出去,让调用者去进行处理,自己不进行具体的处理,此时需要用到throw和throws关键字。

public class Main {
    public static void main(String[] args) {
        try {
            createFile();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
     
    public static void createFile() throws IOException{
        File file = new File("d:/a.txt");
        if(!file.exists())
            file.createNewFile();
    }
}

这段代码和上面一段代码的区别是,在实际的createFile方法中并没有捕获异常,而是用throws关键字声明抛出异常,即告知这个方法的调用者此方法可能会抛出IOException。那么在main方法中调用createFile方法的时候,采用try…catch块进行了异常捕获处理。

当然还可以采用throw关键字手动来抛出异常对象。下面看一个例子:

public class Main {
    public static void main(String[] args) {
        try {
            int[] data = new int[]{1,2,3};
            System.out.println(getDataByIndex(-1,data));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
         
    }
     
    public static int getDataByIndex(int index,int[] data) {
        if(index<0||index>=data.length)
            throw new ArrayIndexOutOfBoundsException("数组下标越界");
        return data[index];
    }
}

3 自定义异常

package com.zr;
/*
自定义注册异常,继承RuntimeException
*/
public class RegistException extends RuntimeException {
//定义无参构造方法
public RegistException() {
super();
}

//定义有参构造方法
public RegistException(String message) {
    super(message);
}

}

package com.zr;

import java.util.Scanner;
/*
对自定义异常RegistException的使用
*/
public class DemoRegistException {
//数据库用户名
static String[] userNames={“张三”,“李四”,“王五”};
public static void main(String[] args) {
//输入注册的用户名
System.out.println(“请输入用户名:”);
Scanner sc=new Scanner(System.in);
String username = sc.next();

    //循环遍历userNames数组,查询用户名是否已经存在
    for (String name : userNames) {
        //如果存在,抛出异常,中断程序
        if (name.equals(username)){
            throw new RegistException("用户名已经存在");
        }
    }
    //如果不存在,输出注册成功
    System.out.println("注册成功");
}

}