Java 异常②

📅 2026/8/2 5:27:02 👁️ 阅读次数 📝 编程学习
Java 异常②

目录

  • 文章摘要
  • 1. throw 处理异常
  • 2. throws 声明异常
  • 3. throw 和 throws 的区别
  • 4. finally
  • 5. 自定义异常类

文章摘要

本文详细讲解了Java异常处理中的三个关键机制:
throw用于主动抛出异常对象,需配合try-catch处理;throws声明方法可能抛出的异常类型,将异常传递给调用者处理;finally块确保无论是否发生异常都能执行,常用于资源释放。文章通过代码示例对比了throw和throws在作用、位置、语法等方面的区别,并介绍了自定义异常类的创建方法及其优点。

1. throw 处理异常

throw : 主动抛出一个异常对象。 语法 :throw 异常对象;

1.1 throw 示例

publicclassTest{publicstaticvoidmain(String[]args){intage=-1;if(age<0){thrownewRuntimeException("年龄不能为负数");}System.out.println("正常执行");}}



age < 0

new RuntimeException 对象

throw 抛出

程序异常结束

后面的System.out.println("正常执行");不会执行

1.2 throw 和 try-catch的结合
如果抛出的异常有人捕获:

publicclassTest{publicstaticvoidtest(int[]a){try{if(a==null){thrownewNullPointerException();}}catch(NullPointerExceptione){e.printStackTrace();}System.out.println("执行剩余代码");}publicstaticvoidmain(String[]args){int[]a=null;test(a);}}

2. throws 声明异常

声明一个方法可能会抛出的异常,把异常交给调用者处理
语法 : 修饰符 返回值 方法名(参数) throws 异常类型 { }

2.1 throws 示例

publicclassTest{publicstaticvoidmain(String[]args)throwsIOException{readFile();}publicstaticvoidreadFile()throwsIOException{FileInputStreamfis=newFileInputStream("a.txt");}}


编译阶段:

发现FileInputStream可能IOException

检查有没有try-catchthrows

throws

编译通过

运行阶段:

执行new FileInputStream("a.txt")

发现文件不存在

真正产生IOException

程序终止

3. throw 和 throws 的区别

throwthrows
作用主动抛异常声明异常
位置方法内部方法声明处
后面跟异常对象异常类型
是否产生异常不会
数量一次一个可以多个
常用于主动检测错误传递异常责任

4. finally

无论 try 中是否发生异常,finally 中的代码通常都会执行。

语法 :

try{// 可能发生异常的代码}catch(异常类型 e){// 处理异常}finally{// 一定执行的代码}

例子 :

publicclassTest{publicstaticvoidmain(String[]args){try{inta=10/0;}catch(Exceptione){System.out.println("捕获异常");}finally{System.out.println("执行finally");}}}

final 经常用来关闭资源

publicclassTest{publicstaticintgetData(){Scannerin=null;try{in=newScanner(System.in);intdata=in.nextInt();returndata;}catch(InputMismatchExceptione){e.printStackTrace();}finally{System.out.println("关闭Scanner");in.close();}return0;}publicstaticvoidmain(String[]args){intret=getData();}}

如果输入不匹配的数据时发生异常也能关掉资源 ,可以有效减少资源泄露

5. 自定义异常类

根据业务需求,自己创建一个异常类型。

例如 : 自定义一个异常类判断年龄的有效范围

classInvalidAgeExceptionextendsRuntimeException{publicInvalidAgeException(){super();}publicInvalidAgeException(Stringmessage){super(message);}}classStudent{Stringname;intage;publicStudent(intage,Stringname){try{if(age<0||age>120){thrownewInvalidAgeException("年龄非法");}this.age=age;this.name=name;}catch(InvalidAgeExceptione){e.printStackTrace();}}}publicclassTest{publicstaticvoidmain(String[]args){Students1=newStudent(150,"pater");}}

1.super(message);: 调用父类RuntimeException的构造方法,把错误信息保存下来
2.如果想写成编译时异常 ,把extends RuntimeException改为extends Exception
3.处理异常的方式选择try-catch或者throws

自定义异常类的优点:

  • 语义清晰:异常名直接反映业务含义,比如InvalidAgeException
  • 便于维护:一看异常名就知道问题类型
  • 支持分层处理:可以针对不同异常做不同处理逻辑,提升程序灵活性