java 异常 日志_java 异常与记录日志

该博客展示了如何在Java中创建自定义异常类`MyException2`,并扩展了异常处理的功能,包括携带额外的整型字段`x`和自定义的错误消息。在`main`方法中,通过`try-catch`块演示了如何捕获并打印这些自定义异常,以及如何访问和显示异常的详细信息,包括`val()`方法返回的`x`值。
摘要由CSDN通过智能技术生成

packageexceptions;//: exceptions/ExtraFeatures.java//Further embellishment of exception classes.

import static net.mindview.util.Print.*;class MyException2 extendsException {private intx;publicMyException2() {}public MyException2(String msg) { super(msg); }public MyException2(String msg, intx) {super(msg);this.x =x;

}public int val() { returnx; }public String getMessage() { //相当于toString()方法

return "Detail Message: "+ x + " "+ super.getMessage();

}

}public classExtraFeatures {public static void f() throwsMyException2 {

print("Throwing MyException2 from f()");throw newMyException2();

}public static void g() throwsMyException2 {

print("Throwing MyException2 from g()");throw new MyException2("Originated in g()");

}public static void h() throwsMyException2 {

print("Throwing MyException2 from h()");throw new MyException2("Originated in h()", 47);

}public static voidmain(String[] args) {try{

f();

}catch(MyException2 e) {

e.printStackTrace(System.out);

}try{

g();

}catch(MyException2 e) {

e.printStackTrace(System.out);

}try{

h();

}catch(MyException2 e) {

e.printStackTrace(System.out);

System.out.println("e.val() = " +e.val());

}

}

}/*Output:

Throwing MyException2 from f()

MyException2: Detail Message: 0 null

at ExtraFeatures.f(ExtraFeatures.java:22)

at ExtraFeatures.main(ExtraFeatures.java:34)

Throwing MyException2 from g()

MyException2: Detail Message: 0 Originated in g()

at ExtraFeatures.g(ExtraFeatures.java:26)

at ExtraFeatures.main(ExtraFeatures.java:39)

Throwing MyException2 from h()

MyException2: Detail Message: 47 Originated in h()

at ExtraFeatures.h(ExtraFeatures.java:30)

at ExtraFeatures.main(ExtraFeatures.java:44)

e.val() = 47*///:~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值