---
title: "Throwable 的妙用"
author: "biqing0427"
date: "2008-03-31T13:36:01Z"
tags: ["Blog", "HTML", "Java", "SUN"]
slug: "throwable"
draft: false
lastmod: "2008-03-31T13:36:01Z"
id: 178018
url: "https://zhouxiaowen.iteye.com/blog/178018"
---

1.Throwable 是java.lang.error 和java.lang.exception的父类，它包括了大部分的错误和异常信息。
由于它是所以得父类，根据这个特性，可以定义捕获异常信息的通用接口。

典型的使用是：
捕获错误发生的类名，函数和行数。

 
```java
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全部继承这个类，比较简洁：

```java
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

```java
public class ParameterException extends NestedException {

	public ParameterException(String msg, Exception e, int id) {
		super(msg, e, id);
	}

}
```


TechnicalException

```java
public class TechnicalException extends NestedException {

	public TechnicalException(String msg, Exception e, int id) {
		super(msg, e, id);
	}

}
```



查考：runtimeexception :
<http://nakata-yf.iteye.com/blog/23569>
<http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/lang/class-use/RuntimeException.html>
<http://www.xrss.cn/Info/8533.Html>
<http://www.javaworld.com/javaworld/jw-11-2007/jw-11-exceptionset.html>
<http://www.javaworld.com/jw-07-1998/jw-07-techniques.html>