关于成链异常Throwable构造函数的问题.

来源:百度知道 编辑:UC知道 时间:2024/05/25 17:18:35
一共有四个.
Throwable()
构造一个将 null 作为其详细消息的新 throwable。
Throwable(String message)
构造带指定详细消息的新 throwable。
Throwable(String message, Throwable cause)
构造一个带指定详细消息和 cause 的新 throwable。
Throwable(Throwable cause)
构造一个带指定 cause 和 (cause==null ? null :cause.toString())(它通常包含类和 cause 的详细消息)的详细消息的新 throwable。

但是我编译以下代码时:
class a {
static ArithmeticException s = new ArithmeticException("call Ari") ;
static void shifang() {
NullPointerException x = new NullPointerException(s) ;
}
}
public class test{
public static void main(String args[]){
try{
a.shifang() ;
}
catch(Exception o){
System.out.println(o.getCause()) ;
}
}
}

编译器提示找不到符号..就是那个ArithmeticException类的异常s那里.

究竟那个构造函数Throwable(Throwable cause) 是什么意思,有谁能解答一下吗?不是把一个异常当做参数传递给顶部异常当原因吗?

楼主是不是想要做自定义异常?
代码错误主要在于这句:NullPointerException x = new NullPointerException(s) ;
虽然NullPointerException间接继承与Throwable,可是,NullPointerException 本身只有两个构造函数,public NullPointerException() {super();}和 public NullPointerException(String s) {super(s);},所以,你这样的写法是会报错的。
如果只是想要获取“call Ari”这个异常的话,你可以这样写:
class a{
static ArithmeticException s = new ArithmeticException("call Ari");

static void shifang() {
NullPointerException x = new NullPointerException(s.getMessage());
throw x;
}
}

public class test {
public static void main(String args[]) {
try {
a.shifang();
} catch (Exception o) {
System.out.println(o.toString());
}
}
}

希望能帮到你

xiliantian正解

构造器是不被继承的。NullPointerException 虽然继承了Throwable,但继承不了Throwable的构造器。