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轻松入门经典教程【完整版】

  • 相关阅读:
    POJ 2209
    POJ 2196
    POJ 2215
    POJ 2192
    POJ 2195
    POJ 2181
    POJ 2182
    POJ 2159
    POJ 2153
    字符设备驱动 —— 字符设备驱动框架
  • 原文地址:https://www.cnblogs.com/cenliang/p/5630926.html
Copyright © 2011-2022 走看看