---
title: "java Exception"
author: "unnKoel"
date: "2014-12-11T12:20:11Z"
tags: []
categories: ["编程语言"]
slug: "java-exception"
draft: false
lastmod: "2014-12-11T19:56:44Z"
id: 2165129
url: "https://unnkoel.iteye.com/blog/2165129"
---

**1.Exception家谱**

 

   Exception继承Throwable基类，而Throwable类现实了Serializable接口，即Throwable自身以及它的子类都是可序列化的。

   (1)Throwable类

        主要成员变量：

        detailMessage:String                         用于描述异常信息

        cause:Throwable                               指向引起本异常的上一个异常，作用于组成异常链，

                                                                   可命名为”原因异常“

        stackTrace:StackTraceElement\[]       异常栈信息，就是一个StackTraceElement的数组，

                                                                   StackTraceElement见下面类介绍

        主要成员方法：

        printStackTrace():void                        输出异常信息。首先打印本异常类全路径、detailMessage，

                                                                   和异常栈信息，再指向cause，递归输出整个异常链的信息

                           

   (2)Exception类

       Exception类没什么可说的，就定义了多个不同类型的构造方法，每个构造方法，都调用基类Throwable

       的相应构造方法。

  

   (3)StackTraceElement类

       主要成员变量：

       declaringClass:String                            发生异常的类全路径名

       methodName:String                              发生异常的类方法名

       fileName:String                                     发生异常的类文件名

       lineNumber:int                                      发生的异常在类代码的第几行

 

   下面贴上类图，如下：

     
![](http://dl2.iteye.com/upload/attachment/0104/2913/6eb3a588-161f-38b1-8824-7b209ce2cc36.jpg)  
 

**2.模范SQLException写的异常类**

  

```
package com.wind.DbTec.sqlpkg;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * 模范SQLException实现 探究Iterable接口的实现，链表的实现
 * 
 * @author zhouyanjun
 * @version 1.0 2014-12-9
 */
public class MyException extends Exception implements Iterable<Throwable> {

	public MyException(Throwable throwable) {
		super(throwable);
	}

	/**
	 * 设置下一个相关异常
	 * 
	 * @param ex
	 */
	public void setNextException(MyException ex) {
		MyException current = this;
		for (;;) {
			MyException next = current.next;
			if (next != null) {
				current = next;
				continue;
			}
			if (nextUpdater.compareAndSet(current, null, ex)) {
				return;
			}
			current = current.next;
		}
	}

	/**
	 * 异常迭代方法，用于遍历异常，实现了Iterable迭代器的类，可以在foreach语句下遍历
	 */
	public Iterator<Throwable> iterator() {
		return new Iterator<Throwable>() {
			MyException nextException = MyException.this;
			Throwable cause = null;

			public boolean hasNext() {
				if (nextException != null || cause != null) {
					return true;
				}
				return false;
			}

			public Throwable next() {
				Throwable throwable = null;
				if (cause == null && nextException != null) {
					throwable = nextException;
					cause = nextException.getCause();
					nextException = nextException.getNextException();
				} else if (cause != null) {
					throwable = cause;
					cause = cause.getCause();
				} else {
					throw new NoSuchElementException();
				}
				return throwable;
			}

			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}

	/**
	 * public Iterator<Throwable> iterator() { return new Iterator<Throwable>()
	 * { MyException firstException = MyException.this; MyException
	 * nextException = firstException.getNextException(); Throwable cause =
	 * firstException.getCause();
	 * 
	 * public boolean hasNext() { if (firstException != null || nextException !=
	 * null || cause != null) { return true; } return false; }
	 * 
	 * public Throwable next() { Throwable throwable = null; if (firstException
	 * != null) { throwable = firstException; firstException = null; } else if
	 * (cause != null) { throwable = cause; cause = cause.getCause(); } else if
	 * (nextException != null) { throwable = nextException; cause =
	 * next.getCause(); nextException = nextException.getNextException(); } else
	 * throw new NoSuchElementException(); return throwable; }
	 * 
	 * public void remove() { throw new UnsupportedOperationException(); } }; }
	 **/

	private MyException getNextException() {
		return (next);
	}

	private volatile MyException next; // 下一个异常，用于实现链表

	private static final long serialVersionUID = 7376914647474065999L;

	private static final AtomicReferenceFieldUpdater<MyException, MyException> nextUpdater = AtomicReferenceFieldUpdater
		.newUpdater(MyException.class, MyException.class, "next"); // 原子对象字段更新器，对Volatile变量进行值更新

	public static void main(String[] args) {
		NoSuchElementException noSEleException = new NoSuchElementException();
		UnsupportedOperationException unSuOperaException = new UnsupportedOperationException();
		MyException head = new MyException(noSEleException);
		MyException one = new MyException(unSuOperaException);
		head.setNextException(one);
		for (Throwable throwable : head) {
			throwable.printStackTrace();
		}
	}
}
```

   

   (1) MyException继承Exception，实现了自己的异常类。

   (2)另外MyException定义了一个next成员变量，指向下一个MyException类型的异常，以实现链表。MyEx- ception还实现了Iterable接口，用于迭代遍历链表。