Think-java_12

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();
		}
	}
}

 

 

 

 

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值