Throwable类详解

Throwable 类是 Java 语言中所有错误或异常的父类。只有当对象是此类(或其子类之一)的实例时,才能通过 Java 虚拟机或者 Java throw 语句抛出。类似地,只有此类或其子类之一才可以是 catch 子句中的参数类型。


Throwable 类及其子类有两个构造方法,一个不带参数,另一个带有 String 参数,此参数可用于生成详细消息。此外,这些子类很可能有与其相关联的 cause,因此也应有两个构造方法,一个带 Throwable (cause),一个带 String(详细消息)和 Throwable (cause)。

方法如下:

返回类型方法名称方法说明
ThrowablefillInStackTrace()在异常堆栈跟踪中填充。
ThrowablegetCause()返回此 throwable 的 cause;如果 cause 不存在或未知,则返回 null。
StringgetLocalizedMessage()创建此 throwable 的本地化描述。
StringgetMessage()返回此 throwable 的详细消息字符串。
StackTraceElement[]getStackTrace()提供编程访问由 printStackTrace() 输出的堆栈跟踪信息。
ThrowableinitCause(Throwable cause)将此 throwable 的 cause 初始化为指定值。
voidprintStackTrace()将此 throwable 及其追踪输出至标准错误流。
voidprintStackTrace(PrintStream s)将此 throwable 及其追踪输出到指定的输出流。
voidprintStackTrace(PrintWriter s)将此 throwable 及其追踪输出到指定的 PrintWriter。
voidsetStackTrace(StackTraceElement[] stackTrace)设置将由 getStackTrace() 返回,并由 printStackTrace() 和相关方法输出的堆栈跟踪元素。
StringtoString()返回此 throwable 的简短描述。

对于处理不了的异常 或者需要转型的异常,在方法的声明处通过throws语句声明抛出异常,而throw语句就是用于在方法内抛出一个异常。对于在方法中可能出现的异常,如果不想在方法中捕获,可以使用throws声明一个抛出异常。例如:

public int read() throws IOException{
}
//或者
public int write() throws IOException,
 IllegalAccessException{

}

throw用于在方法体内手动抛出一个异常。

语法:throw 异常名;

例如:

public class Test{
    public static void main(String[] args){
        try{
        System.out.println("从这里开始");
        throw new Exception("用户产生异常");//手动抛出异常
        }catch(Exception e){//捕获并处理异常
            System.out.println("已经捕获异常");
        }

    }
}

因为已经在方法中处理了异常,所以不需要在方法声明处使用throws。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值