zoukankan      html  css  js  c++  java
  • JavaSE 基础 第49节 手动抛出异常

    2016-06-30

    1 手动抛出异常
    throw exception;参数exception表示要抛出的一场对象,该对象是throwable类
    的子类,而且只能够是一个。

    2 try catch finally 是可以嵌套使用的。

    package com.java1995;
    /**
     * 1 手动抛出异常
     * @author Administrator
     *
     */
    public class ThrowTest {
        
        public static void main(String[] args) {
            
            ThrowTest t=new ThrowTest();
            
            try {
                t.test();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println(e.getMessage());
            }
        }
        
        public void test() throws Exception{
            
            throw new Exception("这是手动抛出来的");
        }
    
    }

    package com.java1995;
    /**
     * 2 try...catch...finally的嵌套
     * 数据库连接池中遇到的比较多
     * @author Administrator
     *
     */
    public class TryCatchFinallyTest {
        
        public static void main(String[] args) {
            
            double a=Math.random();
            
            try{
                if(a>0.5){
                    System.out.println(a+",程序不报错");
                }else{
                    throw new Exception();
                }
                
            }catch(Exception e){
                
                System.out.println("这是外层捕获的对象"+e);
                try{
                    a=1/0;
                }catch(ArithmeticException e1){
                    System.out.println("这是内层捕获的对象"+e1);
                }finally{
                    System.out.println("这是内层的finally块");
                }
            }finally{
                System.out.println("这是外层的finally块");
            }
            
        }
    }

    【参考资料】

    [1] Java轻松入门经典教程【完整版】

  • 相关阅读:
    linux系统root用户忘记密码的重置方法
    Linux系统的初始化配置
    LINUX awk 函数
    随机产生一个密码,要求同时包含大小写以及数字这三种字符。
    sed 函数 linux
    grep 函数
    linux sort 函数
    从零开始的JAVA -4. 运算符与表达式
    cp
    PATH
  • 原文地址:https://www.cnblogs.com/cenliang/p/5630926.html
Copyright © 2011-2022 走看看