Think-java_12

来源:互联网 发布:淘宝卖家规则及处罚 编辑:程序博客网 时间:2024/05/01 17:54

1、编写一个类,在其main ()方法中的try块里抛出一个Exception类的对象。传递一个字符串参数给Exception的构造器。在catch子句里捕获此异常对象,并且打印字串参数。添加一个finally子句,打印一条信息以证明这里确实得到了执行。


// 自定义的 Exception1 类要继承  Exception class Exception1 extends Exception {    public Exception1(String msg) {        super(msg);        System.out.println("Exception1(String msg)");    }}public class exprion_1 {    public static void f() throws Exception1 {        System.out.println("Throwing MyException from f()");// 2、传递一个字符串参数给Exception的构造器        throw new Exception1("From f()");    }    public static void main(String[] args) {        try {// 1、try块里抛出一个Exception类的对象            f();        } catch(Exception1 e) {// 3、在catch子句里捕获此异常对象,并且打印字串参数。            System.err.println("Caught Exception1");            e.printStackTrace();        } finally {// 4、添加一个finally子句,打印一条信息以证明这里确实得到了执行。            System.out.println("Made it to finally");        }    }}

2、

// 使用extends关键字建立一个自定义异常类,class Exception4 extends Exception {private String msg;// 为这个类写一个接受字符参数的构造器Exception4(String msg) {super(msg);System.out.println("Exception4()");        // 把此参数保存在对象内部的字符串引用中this.msg = msg;}    // 写一个方法显示次字符串protected void showS() {System.out.println("Message from Exception4: " + msg);}}public class Ex4 {    // 定义方法跑出异常public static void f() throws Exception4 {System.out.println("f()");throw new Exception4("Ouch from f()");}public static void main(String[] args) {        // 使用try-catch子句,对这个新异常进行测试try {f();} catch(Exception4 e) {System.err.println("Caught Exception4");e.printStackTrace();e.showS();}}}


0 0
原创粉丝点击