源码分析七(java.lang包之IllegalArgumentException类)

一:IllegalArgumentException非法参数类,这个类继承父类RuntimeException

1 public
2 class IllegalArgumentException extends RuntimeException

 

重载的几个构造方法都是直接调用父类的构造方法:

//无参数构造器,默认构造器
public IllegalArgumentException() {
    super();
    }

   //参数为字符串String的构造器
    public IllegalArgumentException(String s) {
    super(s);
    }

    //参数为String以及Throwable两个参数构造器
    public IllegalArgumentException(String message, Throwable cause) {
        super(message, cause);
    }
 
    //参数为Throwable的构造器
    public IllegalArgumentException(Throwable cause) {
        super(cause);
    }

    private static final long serialVersionUID = -5365630128856068164L;

 

RuntimeException类是直接继承extends Exception类

public class RuntimeException extends Exception {
    static final long serialVersionUID = -7034897190745766939L;

     
    public RuntimeException() {
    super();
    }

    
    public RuntimeException(String message) {
    super(message);
    }

    
    public RuntimeException(String message, Throwable cause) {
        super(message, cause);
    }

    
    public RuntimeException(Throwable cause) {
        super(cause);
    }

Exception类:

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

    
    public Exception() {
    super();
    }

     
    public Exception(String message) {
    super(message);
    }

   
    public Exception(String message, Throwable cause) {
        super(message, cause);
    }

     
    public Exception(Throwable cause) {
        super(cause);
    }
}

而Exception类是继承Throwable类

1 //无参数构造器 
2 public Throwable() {
3         fillInStackTrace();
4     }
5 
6 //调用native方法,底层是c或者c++语言实现
7  public synchronized native Throwable fillInStackTrace();

 

//参数为String的构造器,描述异常信息
public Throwable(String message) {
        fillInStackTrace();
        detailMessage = message;
    }

private String detailMessage;

 

1 //参数为String以及Throwable的构造器 
2 public Throwable(String message, Throwable cause) {
3         fillInStackTrace();
4         detailMessage = message;
5         this.cause = cause;
6     }

 

//参数为Throwable的构造器 
public Throwable(Throwable cause) {
        fillInStackTrace();
        detailMessage = (cause==null ? null : cause.toString());
        this.cause = cause;
    }

 

再来看一下Throwable中的其他的方法:

//异常的详细信息,就是在构造方法中封装的message
 public String getMessage() {
        return detailMessage;
    }

  

//直接调用getMessage方法,返回的也是异常的描述信息  
 public String getLocalizedMessage() {
        return getMessage();
    }

  

//获取这个异常对象,因为这个cause异常对象初始化的时候
是this,就是它本身,所以如果没有变,就是null,否则是cause

private Throwable cause = this;
 
public Throwable getCause() {
        return (cause==this ? null : cause);
    }

  

 

二:自定义异常类

如果我们想要自定义异常类,只需要继承RuntimeException或者Exception类,然后

在构造方法中调用父类的构造方法就可以了。

 

    原文作者:warrior1234
    原文地址: https://www.cnblogs.com/warrior4236/p/6653887.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞