java异常处理机制

第0章:简介

1.主要异常类结构图

2.参考网站

http://blog.csdn.net/ilibaba/article/details/3965359

http://blog.sina.com.cn/s/blog_6433391301010bq9.html

http://www.cnblogs.com/focusj/archive/2011/12/26/2301524.html

http://cwfmaker.iteye.com/blog/1415737

http://g.kehou.com/t1006012468.html


3.札记

1)异常处理的流程:
① 遇到错误,方法立即结束,并不返回一个值;同时,抛出一个异常对象 。
② 调用该方法的程序也不会继续执行下去,而是搜索一个可以处理该异常的异常处理器,并执行其中的代码 。

2)异常的分类:
① 异常的继承结构:基类为Throwable,Error和Exception继承Throwable,RuntimeException和IOException等继承Exception,具体的RuntimeException继承RuntimeException。
② Error和RuntimeException及其子类成为未检查异常(unchecked),其它异常成为已检查异常(checked)。

3)Error体系 :
      Error类体系描述了Java运行系统中的内部错误以及资源耗尽的情形。应用程序不应该抛出这种类型的对象(一般是由虚拟机抛出)。如果出现这种错误,除了尽力使程序安全退出外,在其他方面是无能为力的。所以,在进行程序设计时,应该更关注Exception体系。


第1章:自定义异常处理实例

(1)自定义RuntimeException抽象类


package com.mcc.core.exception;

/**
 * 自定义RuntimeException抽象类
 * copy from spring core package
 * @author <a href="mailto:417877417@qq.com">menergy</a>
 * @version 2013-11-4
 */
public abstract class NestedRuntimeException extends RuntimeException {
    
    private static final long serialVersionUID = -8196151131036307843L;
    
    static{
        //加载NestedExceptionUtils类,避免classloader死锁
        NestedExceptionUtils.class.getName();
    }
    
    /**
     * 构造带指定详细消息的新 throwable。Cause 尚未进行初始化,可在以后通过调用 initCause(java.lang.Throwable) 来初始化
     * @param msg 详细消息
     */
    public NestedRuntimeException(String msg) {
        super(msg);
    }
    
    /**
     * 构造一个带指定详细消息和 cause 的新 throwable。Cause 进行了初始化,不可再调用initCause(java.lang.Throwable) 来初始化,否则报错
     * @param msg 详细消息
     * @param cause 原因
     */
    public NestedRuntimeException(String msg, Throwable cause) {
        super(msg, cause);
    }
    
    /**
     * 返回详细异常信息
     */
    @Override
    public String getMessage() {
        return NestedExceptionUtils.buildMessage(super.getMessage(), getCause());
    }
    
    /**
     * 获取根异常
     *
     * @return
     */
    public Throwable getRootCause() {
        Throwable rootCause = null;
        Throwable cause = getCause();
        while (cause != null && cause != rootCause) {
            rootCause = cause;
            cause = cause.getCause();
        }
        return rootCause;
    }
    
    /**
     * 获取关键异常(根异常或当前异常)
     *
     * @return
     */
    public Throwable getMostSpecificCause() {
        Throwable rootCause = getRootCause();
        return (rootCause != null ? rootCause : this);
    }
    
    /**
     * 检查异常是否包括给定类型的异常
     *
     * @param exType 异常类型
     * @return
     */
    public boolean contains(Class exType) {
        if (exType == null) {
            return false;
        }
        if (exType.isInstance(this)) {
            return true;
        }
        Throwable cause = getCause();
        if (cause == this) {
            return false;
        }
        if (cause instanceof NestedRuntimeException) {
            return ((NestedRuntimeException) cause).contains(exType);
        }
        else {
            while (cause != null) {
                if (exType.isInstance(cause)) {
                    return true;
                }
                if (cause.getCause() == cause) {
                    break;
                }
                cause = cause.getCause();
            }
            return false;
        }
    }
    
 

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}

(2)自定义IOException抽象类


package com.mcc.core.exception;

import java.io.IOException;

/**
 *自定义IOException抽象类
 *copy from spring core package
 * @author <a href="mailto:417877417@qq.com">menergy</a>
 * @version 2013-11-4
 */
public abstract class NestedIOException extends IOException {

    private static final long serialVersionUID = 6172677566732397256L;
    
    static{
        //加载NestedExceptionUtils类,避免classloader死锁
        NestedExceptionUtils.class.getName();
    }
    
    /**
     * 构造带指定详细消息的新 throwable。Cause 尚未进行初始化,可在以后通过调用 initCause(java.lang.Throwable) 来初始化
     * @param msg 详细消息
     */
    public NestedIOException(String msg) {
        super(msg);
    }
    
    /**
     * 构造一个带指定详细消息和 cause 的新 throwable。Cause 进行了初始化,不可再调用initCause(java.lang.Throwable) 来初始化,否则报错
     * @param msg 详细消息
     * @param cause 原因
     */
    public NestedIOException(String msg, Throwable cause) {
        super(msg);
        initCause(cause);
    }
    
    /**
     * 返回详细异常信息
     */
    @Override
    public String getMessage() {
        return NestedExceptionUtils.buildMessage(super.getMessage(), getCause());
    }

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}

(3)自定义Exception抽象类


package com.mcc.core.exception;

/**
 *自定义Exception抽象类
 *copy from spring core package
 * @author <a href="mailto:417877417@qq.com">menergy</a>
 * @version 2013-11-4
 */
public class NestedCheckedException extends Exception {

    private static final long serialVersionUID = 3668622597443799011L;
    
    static{
        //加载NestedExceptionUtils类,避免classloader死锁
        NestedExceptionUtils.class.getName();
    }
    
    /**
     * 构造带指定详细消息的新 throwable。Cause 尚未进行初始化,可在以后通过调用 initCause(java.lang.Throwable) 来初始化
     * @param msg 详细消息
     */
    public NestedCheckedException(String msg) {
        super(msg);
    }
    
    /**
     * 构造一个带指定详细消息和 cause 的新 throwable。Cause 进行了初始化,不可再调用initCause(java.lang.Throwable) 来初始化,否则报错
     * @param msg 详细消息
     * @param cause 原因
     */
    public NestedCheckedException(String msg, Throwable cause) {
        super(msg, cause);
    }
    
    /**
     * 返回详细异常信息
     */
    @Override
    public String getMessage() {
        return NestedExceptionUtils.buildMessage(super.getMessage(), getCause());
    }
    
    /**
     * 获取根异常
     *
     * @return
     */
    public Throwable getRootCause() {
        Throwable rootCause = null;
        Throwable cause = getCause();
        while (cause != null && cause != rootCause) {
            rootCause = cause;
            cause = cause.getCause();
        }
        return rootCause;
    }
    
    /**
     * 获取关键异常(根异常或当前异常)
     *
     * @return
     */
    public Throwable getMostSpecificCause() {
        Throwable rootCause = getRootCause();
        return (rootCause != null ? rootCause : this);
    }
    
    /**
     * 检查异常是否包括给定类型的异常
     *
     * @param exType 异常类型
     * @return
     */
    public boolean contains(Class exType) {
        if (exType == null) {
            return false;
        }
        if (exType.isInstance(this)) {
            return true;
        }
        Throwable cause = getCause();
        if (cause == this) {
            return false;
        }
        if (cause instanceof NestedRuntimeException) {
            return ((NestedRuntimeException) cause).contains(exType);
        }
        else {
            while (cause != null) {
                if (exType.isInstance(cause)) {
                    return true;
                }
                if (cause.getCause() == cause) {
                    break;
                }
                cause = cause.getCause();
            }
            return false;
        }
    }

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        try {
            throw new NestedCheckedException("test Exception! ");
        } catch (NestedCheckedException e) {
            e.printStackTrace();
        }
        //System.out.println(2/0);

    }

}

(4)异常工具类


package com.mcc.core.exception;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 异常工具类
 * copy from spring core package
 * @author <a href="mailto:417877417@qq.com">menergy</a>
 * @version 2013-11-4
 */
public abstract class NestedExceptionUtils {
    
    /**
     * 是否是受检查异常
     *
     * @param ex
     * @return
     */
    public static boolean isCheckedException(Throwable ex) {
        return !(ex instanceof RuntimeException || ex instanceof Error);
    }
    
    /**
     *  根据根cause和附加消息生成自定义异常消息
     *
     * @param message 附加消息
     * @param ex 根cause
     * @return
     */
    public static String buildMessage(String message, Throwable ex) {
        if (ex != null) {
            StringBuilder sb = new StringBuilder();
            if (message != null) {
                sb.append(message).append("; ");
            }
            sb.append("nested exception is ").append(ex);
            return sb.toString();
        }
        else {
            return message;
        }
    }
    
    /**
     * 将受检查异常转换为非检查异常
     *
     * @param ex 异常
     * @return
     */
    public static RuntimeException changeToUnchecked(Throwable ex) {
        if (ex instanceof RuntimeException) {
            return (RuntimeException) ex;
        } else {
            return new RuntimeException(ex);
        }
    }

    /**
     * 将栈轨迹信息转化为字符串
     *
     * @param ex 异常
     * @return
     */
    public static String getStackTraceAsString(Throwable ex) {
        StringWriter stringWriter = new StringWriter();
        ex.printStackTrace(new PrintWriter(stringWriter));
        return stringWriter.toString();
    }
    
    /**
     * 判断该异常是否与指定的异常类兼容,即为非检查异常或该异常是指定异常类的子类
     *
     * @param ex 异常
     * @param declaredExceptions  指定的异常类
     * @return
     */
    public static boolean isCompatibleWithThrowsClause(Throwable ex, Class[] declaredExceptions) {
        if (!isCheckedException(ex)) {
            return true;
        }
        if (declaredExceptions != null) {
            int i = 0;
            while (i < declaredExceptions.length) {
                if (declaredExceptions[i].isAssignableFrom(ex.getClass())) {
                    return true;
                }
                i++;
            }
        }
        return false;
    }

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值