• 技术文章 >java >java基础

    java finally处理异常

    小妮浅浅小妮浅浅2021-02-21 10:10:53原创2514

    本教程操作环境:windows7系统、java10版,DELL G3电脑。

    1.说明

    finally是异常处理语句结构的一部分,表示finally里面的代码块一定会执行。

    2.使用注意

    1)finally不能单独使用,必须和try…语句或try…catch语句连用

    2)程序运行时,不论是否发生异常,finally代码块都会执行

    3)除非遇到System.exit方法,否则finally代码块一定会执行

    3.实例

    public class Demo2 {
     
        public static void main(String[] args) {
            try {
                int i = 10/0;
                  System.out.println("i="+i); 
            } catch (ArithmeticException e) {
                  System.out.println("Caught Exception"); 
                System.out.println("e.getMessage(): " + e.getMessage()); 
                System.out.println("e.toString(): " + e.toString()); 
                System.out.println("e.printStackTrace():");
                e.printStackTrace(); 
            } finally {
                System.out.println("run finally");
            }
        }
    }

    运行结果:

    Caught Exception
    e.getMessage(): / by zero
    e.toString(): java.lang.ArithmeticException: / by zero
    e.printStackTrace():
    java.lang.ArithmeticException: / by zero
        at Demo2.main(Demo2.java:6)
    run finally

    以上就就是java中finally处理异常的方法,在使用上结合了之前所学的try语句,运行代码我们会发现,finally部分的语句已经得到执行了。

    专题推荐:java finally处理异常
    品易云
    上一篇:java中try-catch的使用 下一篇:java中finally不执行的分析

    相关文章推荐

    • java中try-catch的使用

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网