try,catch,finally

1.try,catch,finally

  try关键字用来包围可能会出现异常的逻辑代码,它单独无法使用,必须配合catch或者finally使用。Java编译器允许的组合使用形式只有以下三种形式:

  try...catch...;       try....finally......;    try....catch...finally...

  当然catch块可以有多个,注意try块只能有一个,finally块是可选的(但是最多只能有一个finally块)。

  三个块执行的顺序为try—>catch—>finally。

  当然如果没有发生异常,则catch块不会执行。但是finally块无论在什么情况下都是会执行的(这点要非常注意,因此部分情况下,都会将释放资源的操作放在finally块中进行)。

  在有多个catch块的时候,是按照catch块的先后顺序进行匹配的,一旦异常类型被一个catch块匹配,则不会与后面的catch块进行匹配。

  在使用try..catch..finally块的时候,注意千万不要在finally块中使用return,因为finally中的return会覆盖已有的返回值。下面看一个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import  java.io.FileInputStream;
import  java.io.FileNotFoundException;
import  java.io.IOException;
 
 
public  class  Main {
     public  static  void  main(String[] args) {
         String str =  new  Main().openFile();
         System.out.println(str);
         
     }
     
     public  String openFile() {
         try  {
             FileInputStream inputStream =  new  FileInputStream( "d:/a.txt" );
             int  ch = inputStream.read();
             System.out.println( "aaa" );
             return  "step1" ;
         catch  (FileNotFoundException e) {
             System.out.println( "file not found" );
             return  "step2" ;
         } catch  (IOException e) {
             System.out.println( "io exception" );
             return  "step3" ;
         } finally {
             System.out.println( "finally block" );
             //return "finally";
         }
     }
}

  这段程序的输出结果为:

  可以看出,在try块中发生FileNotFoundException之后,就跳到第一个catch块,打印"file not found"信息,并将"step2"赋值给返回值,然后执行finally块,最后将返回值返回。

  从这个例子说明,无论try块或者catch块中是否包含return语句,都会执行finally块。

  如果将这个程序稍微修改一下,将finally块中的return语句注释去掉,运行结果是:

  

  最后打印出的是"finally",返回值被重新覆盖了。

  因此如果方法有返回值,切忌不要再finally中使用return,这样会使得程序结构变得混乱。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值