try,catch,finally测试_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > try,catch,finally测试

try,catch,finally测试

 2017/11/27 0:58:35  陶永攀  程序员俱乐部  我要评论(0)
  • 摘要:finally是在任何情况下都会执行的:①当try中有return语句的时候,测试如下:packagestudy.base_study;/***CreatedbyTaoyongpanon2017/11/26.*测试trycatchfinally的执行顺序*/publicclassTryTest{publicstaticinttest1(){try{return1;}catch(Exceptione){e.printStackTrace();}finally{System.out.println
  • 标签:测试 all

? ? ? ? finally是在任何情况下都会执行的:

? ? ? ?①当try中有return语句的时候,测试如下:

class="java" name="code">package study.base_study;

/**
 * Created by Taoyongpan on 2017/11/26.
 * 测试 try catch  finally的执行顺序
 */
public class TryTest {

    public static int test1(){
        try {
            return 1;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("finally方法");
        }
        return 0;
    }

    public static void main(String[] args){
        System.out.println(test1());
    }
}

?测试结果如下:

?

finally方法

1

?

Process finished with exit code 0

?

②当 报错抛出异常的时候,测试如下:

package study.base_study;

/**
 * Created by Taoyongpan on 2017/11/26.
 * 测试 try catch  finally的执行顺序
 */
public class TryTest {

    public static int test1(){
        try {
            return 1/0;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("finally方法");
        }
        return 0;
    }

    public static void main(String[] args){
        System.out.println(test1());
    }
}

?测试结果如下:

finally方法

java.lang.ArithmeticException: / by zero

0

at study.base_study.TryTest.test1(TryTest.java:11)

at study.base_study.TryTest.main(TryTest.java:21)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.lang.reflect.Method.invoke(Method.java:498)

at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

?

Process finished with exit code 0

?

③当finally方法中也有 return语句的时候,try中的return将不再执行,测试如下:

package study.base_study;

/**
 * Created by Taoyongpan on 2017/11/26.
 * 测试 try catch  finally的执行顺序
 */
public class TryTest {

    public static int test1(){
        try {
            return 1;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("finally方法");
            return 0;
        }

    }

    public static void main(String[] args){
        System.out.println(test1());
    }
}

?测试结果如下:

finally方法

0

?

Process finished with exit code 0

?

上一篇: Java多线程--volatile 下一篇: 没有下一篇了!
发表评论
用户名: 匿名