自定义异常及Exception有参构造函数源码解析

本文介绍了如何创建一个自定义异常类`MyException`,它继承自`Exception`。然后详细解析了`Exception`和`Throwable`类的源码,展示了异常是如何被构造和填充堆栈轨迹的。接着,通过`Height`类的方法`check`演示了如何在方法中抛出自定义异常,并在`HeightTest`测试类中捕获并打印异常堆栈轨迹。
摘要由CSDN通过智能技术生成

1、写一个自定义的异常类(MyException),让其继承Exception.

public class MyException extends Exception {
    static final long serialVersionUID = -3387516993124229948L;
    public MyException() {
    }
    public MyException(String s){
        super(s);
    }

}

2、分析super(s)(这里只是源码解析,看得懂就看,看不懂就到第三步)

public class Exception extends Throwable {
    static final long serialVersionUID = -3387516993124229948L;    

    public Exception(String message) {
        super(message);
    }
}
public class Throwable implements Serializable {

    private static final long serialVersionUID = -3042686055658047285L;
 
    private String detailMessage; 

    private transient Object backtrace;

    private StackTraceElement[] stackTrace = UNASSIGNED_STACK;

    private native Throwable fillInStackTrace(int dummy);

    private static final StackTraceElement[] UNASSIGNED_STACK 
    = new StackTraceElement[0];

    public synchronized Throwable fillInStackTrace() {
        if (stackTrace != null ||
            backtrace != null /* Out of protocol state */ ) {
            fillInStackTrace(0);
            stackTrace = UNASSIGNED_STACK;
        }
        return this;
    }
 
    public Throwable(String message) {
        fillInStackTrace();
        detailMessage = message;
    } 
}
public final class StackTraceElement implements java.io.Serializable {
    // Normally initialized by VM (public constructor added in 1.5)
    private String declaringClass;
    private String methodName;
    private String fileName;
    private int    lineNumber;
}

3、写一个方法里面抛出自己的异常

public class Height {

    private int maxHeight=200;
    private int minHeight=145;
    /**
     *
     * @param stature 身高
     * @throws MyException
     */
    public void check(int stature) throws MyException {
        if (stature > maxHeight || stature < minHeight) {
            //身高不在正常范围时抛出异常
            throw new MyException("身高不正常,身高应该是145--200之间");
        } else {
            System.out.println("身高正常,你的身高是" + stature);
        }
    }
}

4、写一个测试方法(抛出异常)

public class HeightTest {
    public static void main(String[] args) {
        int height=100;
        Height hei=new Height();
        try{
            hei.check(height);
        } catch (MyException e) {
            e.printStackTrace();
        }
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值