• 2009-01-06

    try-catch-exception-return执行顺序 - [java基础]

    版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
    http://allantaylor.blogbus.com/logs/33474565.html

    import java.io.FileInputStream;

    public class TestTryCatchException {

     public int amethod()
     {
            try {
                   FileInputStream dis =new FileInputStream("Hello.txt"); //1,抛出异常
          }catch ( Exception ex) {
                     System.out.println("No such file found");   //2.catch捕获异常,并执行
                     return -1;                               //4,return 返回
          }finally{
                     System.out.println("Doing finally");       //3.finally一定会执行,在return之前。
                     return 2;
          }
         // return 0; //finally 有返回,return 0是错误的
         }
     /**
      * finally的return优先级最高 --> 其次 catch中的 return ---> 再次 finally之后的return 语句
      * 说明catch的return 2; 是无效的,因为return 3; 首要地返回了结果。
      * 如果让try执行return,结果也是表明try的return 1;是无效的!
      * @return
      */
     public int tryThis()
       {
         try{
           System.out.println("1-");
           throw new Exception();
            //return 1; 抛出异常 的后面不能有return ,编译不通过
         }catch(Exception ex){
           System.out.println("2-");
           return 2; //finally 若没有return 会返回 改语句  
         }finally{
           System.out.println("4-");
           return 3;  //return  最高返回 finally 中有返回语句 finally之后的就不能有其它语句
         }
         //System.out.println("5"); 
       }


     public static void main(String[] args){
      TestTryCatchException t = new TestTryCatchException();
      System.out.println ("--------测试 1 -------");
      System.out.println ("-------- "+t.amethod());
      System.out.println ("--------测试 2 -------");
      System.out.println("-------- "+t.tryThis());
     }
    }


    历史上的今天:


    收藏到:Del.icio.us