1,常见的异常
在Java中,将程序执⾏过程中发⽣的不正常行为称为异常
1.1 算数异常
public static void main(String[] args) {
System.out.println(10 / 0);
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at LibrarySystem.main(LibrarySystem.java:97)
1.2 数组越界异常
public static void main(String[] args) {
int[] array = {1, 2, 3};
System.out.println(array [100]);
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 100
out of bounds for length 3
at LibrarySystem.main(LibrarySystem.java:98)
1.3 空指针异常
public static void main(String[] args) {
int[] array = null;
System.out.println(array.length);
}
Exception in thread "main" java.lang.NullPointerException: Cannot read the
array length because "array" is null
at LibrarySystem.main(LibrarySystem.java:98)
Java中不同类型的异常,都有与其对应的类来进行描述

1.4 异常的分类
2,异常的处理
boolean ret = false;
ret = 登陆游戏();
if (!ret) {
处理登陆游戏错误;
return;
}
ret = 开始匹配();
if (!ret) {
处理匹配错误;
return;
}
ret = 游戏确认();
if (!ret) {
处理游戏确认错误;
return;
}
ret = 选择英雄();
if (!ret) {
处理选择英雄错误;
return;
}
ret = 载⼊游戏画⾯();
if (!ret) {
处理载⼊游戏错误;
return;
}
try {
登陆游戏();
开始匹配();
游戏确认();
选择英雄();
载⼊游戏画⾯();
…
} catch (登陆游戏异常) {
处理登陆游戏异常;
} catch (开始匹配异常) {
处理开始匹配异常;
} catch (游戏确认异常) {
处理游戏确认异常;
} catch (选择英雄异常) {
处理选择英雄异常;
} catch (载⼊游戏画⾯异常) {
处理载⼊游戏画⾯异常;
}
在Java中,异常处理主要的5个关键字:throw、try、catch、finally、throws
2.1 异常的抛出-throw
具体语法
throw new XXXException("异常产⽣的原因");
实现⼀个获取数组中任意位置元素的⽅法
public static int getElement(int[] array, int index){
if(null == array){
throw new NullPointerException("传递的数组为null");
}
if(index < 0 || index >= array.length){
throw new ArrayIndexOutOfBoundsException("传递的数组下标越界");
}
return array[index];
}
public static void main(String[] args) {
int[] array = {1,2,3};
getElement(array, 3);
}
注意:
2.2 异常的声明-throws
基本语法
语法格式:
修饰符 返回值类型 ⽅法名(参数列表) throws 异常类型1,异常类型2…{
}
public class Config {
File file;
// FileNotFoundException 继承⾃ IOException
public void OpenConfig(String filename) throws IOException{
if(filename.endsWith(".ini")){
throw new IOException("⽂件不是.ini⽂件");
}
if(filename.equals("config.ini")){
throw new FileNotFoundException("配置⽂件名字不对");
}
// 打开⽂件
}
public void readConfig(){
}
}
调用声明抛出异常的⽅法时,如果该异常是编译时异常/受查异常时,调⽤者必须对该异常进⾏处 理,或者继续使⽤throws抛出
public static void main(String[] args) throws IOException {
Config config = new Config();
config.openConfig("config.ini");
}
2.3 异常的捕获-try-catch捕获并处理异常
throws对异常并没有真正处理,⽽是将异常报告给抛出异常⽅法的调⽤者,由调⽤者处理。如果真正要对异常进⾏处理,就需要try-catch
语法格式:
try{
// 将可能出现异常的代码放在这⾥
}catch(要捕获的异常类型 e){
// 如果try中的代码抛出异常了,此处catch捕获时异常类型与try中抛出的异常类型⼀致
时,或者是try中抛出异常的基类时,就会被捕获到
// 对异常就可以正常处理,处理完成后,跳出try-catch结构,继续执⾏后序代码
}[catch(异常类型 e){
// 对异常进⾏处理
}finally{
// 此处代码⼀定会被执⾏到
}]
注意
public static void main(String[] args) {
int[] array = {1, 2, 3};
try {
System.out.println("before");
// array = null;
System.out.println(array [100]);
System.out.println("after");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("这是个数组下标越界异常");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("这是个空指针异常");
e.printStackTrace();
}
System.out.println("after try catch");
}
如果多个异常的处理⽅式是完全相同,也可以写成这样
catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
…
}
如果异常之间具有⽗⼦关系,⼀定是⼦类异常在前catch,⽗类异常在后catch
2.4 finally
在写程序时,有些特定的代码,不论程序是否发⽣异常,都需要执⾏,⽐如程序中打开的资源:⽹络连接、数据库连接、IO流等,在程序正常或者异常退出时,必须要对资源进进⾏回收。另外,因为异常会引发程序的跳转,可能导致有些语句执⾏不到,finally就是⽤来解决这个问题的
语法格式:
try{
// 可能会发⽣异常的代码
}catch(异常类型 e){
// 对捕获到的异常进⾏处理
}finally{
// 此处的语句⽆论是否发⽣异常,都会被执⾏到
}
// 如果没有抛出异常,或者异常被捕获处理了,这⾥的代码也会执⾏
实现getData⽅法,内部输⼊⼀个整型数字,然后将该数字返回,并再main⽅法中打印
public class TestFinally {
public static int getData(){
Scanner sc = null;
try{
sc = new Scanner(System.in);
int data = sc.nextInt();
return data;
}catch (InputMismatchException e){
e.printStackTrace();
}finally {
System.out.println("finally中代码");
}
System.out.println("try-catch-finally之后代码");
if(null != sc){
sc.close();
}
return 0;
}
public static void main(String[] args) {
int data = getData();
System.out.println(data);
}
}
// 正常输⼊时程序运⾏结果:
100
finally中代码
100
上述程序,如果正常输入,成功接收输入后程序就返回了,try-catch-finally之后的代码根本就没有执行。
finally中的代码一定会执行,所以将sc.close()放在finally就能关闭
public static int func() {
try {
return 10;
} finally {
return 20;
}
}
//20
finally 执⾏的时机是在⽅法返回之前(try或者catch中如果有return会在这个return之前执⾏ finally). 但是如果finally 中也存在return语句,那么就会执⾏finally中的return,从⽽不会执⾏到try 中原有的return
⼀般我们不建议在finally中写return
2.5 异常的处理流程
方法之间是存在相互调用关系的,这种调用关系我们可以用“调用栈”来描述,在JVM中中有一块空间称为“虚拟机栈”专门存储方法之间的调用关系,当代码中出现异常的时候,就可以用 e.printStackTrace(); 的方式查看出现异常代码的调用栈
如果向上⼀直传递都没有合适的⽅法处理异常,最终就会交给JVM处理,程序就会异常终⽌
处理流程
- 程序先执行 try 中的代码
- 如果 try 中的代码出现异常,就会结束 try 中的代码,看和 catch 中的异常类型是否匹配
- 如果找到匹配的异常类型,就会执行 catch 中的代码
- 如果没有找到匹配的异常类型,就会将异常向上传递到上传调用者
- 无论是否找到匹配的异常类型,finally 中的代码都会被执行
- 如果上层调用着也没有处理的了异常,就继续向上传递
- 一直到 main 方法也没有合适的代码处理异常,就交给 JVM 来处理,此时程序就会异常终止
3,自定义异常类
class UserNameException extends Exception {
public UserNameException(String message) {
super(message);
}
}
class PasswordException extends Exception {
public PasswordException(String message) {
super(message);
}
}
- 自定义异常通常会继承自 Exception 或者 RunTimeException
- 继承自 Exception 的异常默认是受查异常
- 继承自 RunTime Exception的异常默认是非受查异常





