相遇'不要钱'

导航

异常的难点和热点


异常流程中的复杂点:

            1.finally语句唯一不被执行的情况是:在finally语句之前执行了System.exit()语句,java.lang.System的静态exit()方法用于终止当前JVM的进程,所以,JVM所执行的java程序
              也随着终止,exit()方法定义如下:
                 public static void exit(int status)
                  exit()方法的参数是一个int型,表示程序被终止时的状态码,0表示正常终止,非0表示非正常终止;




        try{
            System.out.println("1");
            int x=1/0;
            System.out.println("2");
        }
        catch(Exception e){
            System.out.println("3");
         throw e;
        }finally{
        
            System.out.println("4");
        }
        
        System.out.println("5");
    }

//////////1 3 4

public static int show(){
        try{
            System.out.println("=======1======");
            int x=1/0;
            System.out.println("=======2======");
        }catch(Exception e){
            System.out.println("=======3======");
            System.exit(0);//终止本进程
        }finally{
            System.out.println("=======4======");
        }
        System.out.println("=======5======");
        return 0;
    }
================
=======1======
=======3======
        2.return语句 用于退出本方法,返回上层调用方法,如果try...catch..finally中都有return 语句,那么最后的返回值为finally中的返回值;

            public static String method(){
        try{
            System.out.println("1");
            int x=1/0;
            System.out.println("2");
             return "try";
        }
        catch(Exception e){
            System.out.println("3");
              return "catch";
        }finally{
            System.out.println("4");
            return "finally";
        }
    }
===============
1,3,4 finally

            3.finally语句虽然会在return语句之前执行,但是不能通过finally语句在reutn之前改变变量的值,这样做虽然合法,但变量的值不变;
public static int method(){
     int x=0;
     try{
         return x;
     }finally{
         System.out.println("finally");
         x=100;
     }
    }
========================
finally ,0

            4.通常建议在try..catch..finally使用的时候finally语句中不要使用return语句,强行使用虽然不报错,但编译会报警告,因为它将导致两种问题:
              1.finally语句中的return语句覆盖catch或try语句中的return语句;
              2.运行异常;

posted on 2014-05-06 19:28  相遇'不要钱'  阅读(169)  评论(0)    收藏  举报