普通使用:
一、捕获异常
1、捕获异常就是异常的使用:需要用到两个关键字 try 和 catch,并且这两个关键字需要结合起来使用,用 try 来监听可能会抛出异常的代码,一旦捕获到异常,生成异常对象并交给对应的 catch 来处理。
2、基本语法:
try{
//可能抛出异常的代码
} catch (Exception e){
//处理异常
}
具体在代码中的使用过程如下:
3、分析个例子:
public class Test {
public static void main(String[] args) {
try {
int num = 10/10;
} catch (Exception e) {
if(e.getMessage().equals("/ by zero")) {
System.err.println("分母不能为0");
}
}
}
}
注意:程序首先进入try中,若 try 中有异常,则程序运行相应异常的 catch 中的内容;否则,catch 中的内容跳过。可对应多个 catch,然后选择相应异常的 catch 处理。
二、try、catch、finally关键字
1、除了 try 和 catch,还可以使用 finally 关键字来处理异常,finally 的作用?无论程序是否抛出异常,finally 代码块中的代码一定会执行,finally 一般跟在 catch 代码块的后面。
2、基本语法:
try{
//可能抛出异常的代码
} catch (Exception e){
//处理异常的代码
} finally {
//一定会执行的代码
}
进阶使用:
三、关于 try-with-resources 语法
一般形式是 try{}catch(){}
,但是有的时候会看到 try(){}catch(){}
(这里暂不说 finally)
1、try 后面的小括号通常用于定义一个 try-with-resources
语句。这种语句用于确保在 try 块执行完毕后,所有在 try 的 () 中声明的实现了 AutoCloseable
接口的资源(比如:文件、数据库连接)都会自动关闭,不用手动关闭。
格式:括号中可以写多行语句,会自动关闭括号中的资源
try (FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader read = new InputStreamReader(fileInputStream, "GBK");
BufferedReader bufferedReader = new BufferedReader(read);) {
....
....
} catch (Exception e) {
....
}
2、举例:
写成:
try (
InputStream inputStream = httpUrlConnection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
RandomAccessFile oSaveFile = new RandomAccessFile(httpFileName, "rw");
) {
....
....
} catch(){
.....
}
四、面试常问:finally 语句的执行逻辑
1、如果 try
块中的代码没有异常,catch
块将被跳过,finally
块仍然会执行。
无论异常是否发生,finally
块中的代码总会执行
2、如果在 try
或 catch
中发生了 return
语句,finally
仍然会在返回之前执行。
3、finally
中有 return
,会覆盖 try
和 catch
中的返回值。
4、即使没有 catch
块,finally
块依然会执行。
针对第 3 点,举个例子:
public class Test{
public static void main(String[] args) {
System.out.println(testMethod());
}
public static int testMethod() {
try {
System.out.println("Try block executed");
return 1;
} catch (Exception e) {
System.out.println("Catch block executed");
return 2;
} finally {
System.out.println("Finally block executed");
return 3; // `finally` 中的 return 会覆盖之前的返回值
}
}
}
输出:
Try block executed
Finally block executed
3
分析:
- try 块中的 return 1 会被 finally 块中的 return 3 覆盖。虽然 try 块返回了 1,但是由于 finally 块的 return,最终返回的是 3。
- finally 中的 return 会优先于 try 和 catch 中的返回值,保证 finally 中的返回值覆盖前面的返回值。
至此,内容结束,后期会出一个专门针对 面试 常问的 面试题,出专栏!!!