zoukankan      html  css  js  c++  java
  • Java如何使用finally块来捕捉异常?

    在Java编程中,如何使用finally块来捕捉异常?

    此示例显示如何使用finally块来通过使用e.getMessage()捕获运行时异常(Illegalargumentexception)。

    package com.yiibai;
    
    public class UseOfFinally {
        public static void main(String[] argv) {
            new UseOfFinally().doTheWork();
        }
    
        public void doTheWork() {
            Object o = null;
            for (int i = 0; i < 5; i++) {
                try {
                    o = makeObj(i);
                } catch (IllegalArgumentException e) {
                    System.err.println("Error: (" + e.getMessage() + ").");
                    return;
                } finally {
                    System.err.println("All done");
                    if (o == null)
                        System.exit(0);
                }
                System.out.println(o);
            }
        }
    
        public Object makeObj(int type) throws IllegalArgumentException {
            if (type == 1)
                throw new IllegalArgumentException("Don't like type " + type);
            return new Object();
        }
    }
    
    Java

    上述代码示例将产生以下结果 -

    All done
    Error: (Don't like type 1).
    All done
    java.lang.Object@2a139a55
    
    Shell

    示例-2

    以下是java中使用finally块捕捉异常的另一个示例:

    package com.yiibai;
    
    public class UseOfFinally2 {
        public static void main(String[] args) {
            try {
                int data = 25 / 5;
                System.out.println(data);
            } catch (NullPointerException e) {
                System.out.println(e);
            } finally {
                System.out.println("finally block is always executed");
            }
            System.out.println("rest of the code...");
        }
    }
    
    Java

    上述代码示例将产生以下结果 -

    5
    finally block is always executed
    rest of the code...
  • 相关阅读:
    linux下配置java环境
    CentOS6 配置静态IP
    数据库的事务
    MySQL总论
    JDBC面试题
    scp命令
    大数据练习题
    Linux下的Mysql安装 & 配置
    Hive的安装配置 & 基础指令
    本地存储localStorage以及它的封装接口store.js的使用
  • 原文地址:https://www.cnblogs.com/borter/p/9613525.html
Copyright © 2011-2022 走看看