Throwable 的妙用

本文介绍了Java中Throwable类的作用及其如何帮助捕获异常信息,并提出了一个处理RuntimeException的解决方案,通过创建NestedException类及其子类来更好地管理和追踪异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Throwable 是java.lang.error 和java.lang.exception的父类,它包括了大部分的错误和异常信息。
由于它是所以得父类,根据这个特性,可以定义捕获异常信息的通用接口。

典型的使用是:
捕获错误发生的类名,函数和行数。

public static String getStackTraceToString(Throwable throw, boolean multiline, int maxstack) {
if (throw == null)
return null;
StackTraceElement[] traces = throw.getStackTrace();
StringBuffer sb = new StringBuffer();
maxstack = (maxstack == -1 || maxstack > traces.length) ? traces.length : maxstack;
for (int i = 0; i < maxstack; i++) {
if (multiline)
sb.append(traces[i].toString()).append(LINE_SEPARATOR);
else
sb.append(traces[i].toString()).append(";");
}
return sb.toString();
}


2.针对Runexception,我们可以建立一个处理Runexception的父类,而其他类型性的exception全部继承这个类,比较简洁:
public class NestedException extends RuntimeException {

protected Exception nestedException;
protected int issueId;

public NestedException(String msg, Exception e, int id) {
super(msg);
this.nestedException = e;
this.issueId = id;
}

public Exception getNestedException() {
return this.nestedException;
}

public int getIssue() {
return this.issueId;
}

}


假设这里有两种类型错误:
ParameterException
public class ParameterException extends NestedException {

public ParameterException(String msg, Exception e, int id) {
super(msg, e, id);
}

}


TechnicalException
public class TechnicalException extends NestedException {

public TechnicalException(String msg, Exception e, int id) {
super(msg, e, id);
}

}



查考:runtimeexception :
[url]http://nakata-yf.iteye.com/blog/23569[/url]
[url]http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/lang/class-use/RuntimeException.html[/url]
[url]http://www.xrss.cn/Info/8533.Html[/url]
[url]http://www.javaworld.com/javaworld/jw-11-2007/jw-11-exceptionset.html[/url]
[url]http://www.javaworld.com/jw-07-1998/jw-07-techniques.html[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值