Java官方API:https://docs.oracle.com/javase/8/docs/api/
public class Throwable
extends Object
implements Serializable
Throwable
class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java
throw
statement. Similarly, only this class or one of its subclasses can be the argument type in a
catch
clause. For the purposes of compile-time checking of exceptions,
Throwable
and any subclass of
Throwable
that is not also a subclass of either
RuntimeException
or
Error
are regarded as checked exceptions.
Instances of two subclasses, Error
and Exception
, are conventionally used to indicate that exceptional situations have occurred. Typically, these instances are freshly created in the context of the exceptional situation so as to include relevant information (such as stack trace data).
A throwable contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. Over time, a throwable can suppress other throwables from being propagated. Finally, the throwable can also contain a cause: another throwable that caused this throwable to be constructed. The recording of this causal information is referred to as the chained exception facility, as the cause can, itself, have a cause, and so on, leading to a "chain" of exceptions, each caused by another.
One reason that a throwable may have a cause is that the class that throws it is built atop a lower layered abstraction, and an operation on the upper layer fails due to a failure in the lower layer. It would be bad design to let the throwable thrown by the lower layer propagate outward, as it is generally unrelated to the abstraction provided by the upper layer. Further, doing so would tie the API of the upper layer to the details of its implementation, assuming the lower layer's exception was a checked exception. Throwing a "wrapped exception" (i.e., an exception containing a cause) allows the upper layer to communicate the details of the failure to its caller without incurring either of these shortcomings. It preserves the flexibility to change the implementation of the upper layer without changing its API (in particular, the set of exceptions thrown by its methods).
A second reason that a throwable may have a cause is that the method that throws it must conform to a general-purpose interface that does not permit the method to throw the cause directly. For example, suppose a persistent collection conforms to the Collection
interface, and that its persistence is implemented atop java.io
. Suppose the internals of the add
method can throw an IOException
. The implementation can communicate the details of the IOException
to its caller while conforming to the Collection
interface by wrapping the IOException
in an appropriate unchecked exception. (The specification for the persistent collection should indicate that it is capable of throwing such exceptions.)
A cause can be associated with a throwable in two ways: via a constructor that takes the cause as an argument, or via theinitCause(Throwable)
method. New throwable classes that wish to allow causes to be associated with them should provide constructors that take a cause and delegate (perhaps indirectly) to one of the Throwable
constructors that takes a cause. Because the initCause
method is public, it allows a cause to be associated with any throwable, even a "legacy throwable" whose implementation predates the addition of the exception chaining mechanism to Throwable
.
By convention, class Throwable
and its subclasses have two constructors, one that takes no arguments and one that takes a String
argument that can be used to produce a detail message. Further, those subclasses that might likely have a cause associated with them should have two more constructors, one that takes a Throwable
(the cause), and one that takes a String
(the detail message) and a Throwable
(the cause).
Modifier | Constructor and Description |
---|---|
|
Throwable()
Constructs a new throwable with
null as its detail message.
|
|
Throwable(String message)
Constructs a new throwable with the specified detail message.
|
|
Throwable(String message, Throwable cause)
Constructs a new throwable with the specified detail message and cause.
|
protected |
Throwable(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)
Constructs a new throwable with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled.
|
|
Throwable(Throwable cause)
Constructs a new throwable with the specified cause and a detail message of
(cause==null ? null : cause.toString()) (which typically contains the class and detail message of
cause ).
|
Modifier and Type | Method and Description |
---|---|
void |
addSuppressed(Throwable exception)
Appends the specified exception to the exceptions that were suppressed in order to deliver this exception.
|
Throwable |
fillInStackTrace()
Fills in the execution stack trace.
|
Throwable |
getCause()
Returns the cause of this throwable or
null if the cause is nonexistent or unknown.
|
String |
getLocalizedMessage()
Creates a localized description of this throwable.
|
String |
getMessage()
Returns the detail message string of this throwable.
|
StackTraceElement[] |
getStackTrace()
Provides programmatic access to the stack trace information printed by
printStackTrace() .
|
Throwable[] |
getSuppressed()
Returns an array containing all of the exceptions that were suppressed, typically by the
try -with-resources statement, in order to deliver this exception.
|
Throwable |
initCause(Throwable cause)
Initializes the
cause of this throwable to the specified value.
|
void |
printStackTrace()
Prints this throwable and its backtrace to the standard error stream.
|
void |
printStackTrace(PrintStream s)
Prints this throwable and its backtrace to the specified print stream.
|
void |
printStackTrace(PrintWriter s)
Prints this throwable and its backtrace to the specified print writer.
|
void |
setStackTrace(StackTraceElement[] stackTrace)
Sets the stack trace elements that will be returned by
getStackTrace() and printed by
printStackTrace() and related methods.
|
String |
toString()
Returns a short description of this throwable.
|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
public Throwable()
null
as its detail message. The cause is not initialized, and may subsequently be initialized by a call to
initCause(java.lang.Throwable)
.
The fillInStackTrace()
method is called to initialize the stack trace data in the newly created throwable.
public Throwable(String message)
initCause(java.lang.Throwable)
.
The fillInStackTrace()
method is called to initialize the stack trace data in the newly created throwable.
message
- the detail message. The detail message is saved for later retrieval by the
getMessage()
method.
public Throwable(String message, Throwable cause)
Note that the detail message associated with cause
is not automatically incorporated in this throwable's detail message.
The fillInStackTrace()
method is called to initialize the stack trace data in the newly created throwable.
message
- the detail message (which is saved for later retrieval by the
getMessage()
method).
cause
- the cause (which is saved for later retrieval by the
getCause()
method). (A
null
value is permitted, and indicates that the cause is nonexistent or unknown.)
public Throwable(Throwable cause)
(cause==null ? null : cause.toString())
(which typically contains the class and detail message of
cause
). This constructor is useful for throwables that are little more than wrappers for other throwables (for example,
PrivilegedActionException
).
The fillInStackTrace()
method is called to initialize the stack trace data in the newly created throwable.
cause
- the cause (which is saved for later retrieval by the
getCause()
method). (A
null
value is permitted, and indicates that the cause is nonexistent or unknown.)
protected Throwable(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)
getSuppressed()
for this object will return a zero-length array and calls to
addSuppressed(java.lang.Throwable)
that would otherwise append an exception to the suppressed list will have no effect. If the writable stack trace is false, this constructor will not call
fillInStackTrace()
, a
null
will be written to the
stackTrace
field, and subsequent calls to
fillInStackTrace
and
setStackTrace(StackTraceElement[])
will not set the stack trace. If the writable stack trace is false,
getStackTrace()
will return a zero length array.
Note that the other constructors of Throwable
treat suppression as being enabled and the stack trace as being writable. Subclasses of Throwable
should document any conditions under which suppression is disabled and document conditions under which the stack trace is not writable. Disabling of suppression should only occur in exceptional circumstances where special requirements exist, such as a virtual machine reusing exception objects under low-memory situations. Circumstances where a given exception object is repeatedly caught and rethrown, such as to implement control flow between two sub-systems, is another situation where immutable throwable objects would be appropriate.
message
- the detail message.
cause
- the cause. (A
null
value is permitted, and indicates that the cause is nonexistent or unknown.)
enableSuppression
- whether or not suppression is enabled or disabled
writableStackTrace
- whether or not the stack trace should be writable
OutOfMemoryError
,
NullPointerException
,
ArithmeticException
public String getMessage()
Throwable
instance (which may be
null
).
public String getLocalizedMessage()
getMessage()
.
public Throwable getCause()
null
if the cause is nonexistent or unknown. (The cause is the throwable that caused this throwable to get thrown.)
This implementation returns the cause that was supplied via one of the constructors requiring a Throwable
, or that was set after creation with the initCause(Throwable)
method. While it is typically unnecessary to override this method, a subclass can override it to return a cause set by some other means. This is appropriate for a "legacy chained throwable" that predates the addition of chained exceptions to Throwable
. Note that it is not necessary to override any of the PrintStackTrace
methods, all of which invoke the getCause
method to determine the cause of a throwable.
null
if the cause is nonexistent or unknown.
public Throwable initCause(Throwable cause)
This method can be called at most once. It is generally called from within the constructor, or immediately after creating the throwable. If this throwable was created with Throwable(Throwable)
or Throwable(String,Throwable)
, this method cannot be called even once.
An example of using this method on a legacy throwable type without other support for setting the cause is:
try { lowLevelOp(); } catch (LowLevelException le) { throw (HighLevelException) new HighLevelException().initCause(le); // Legacy constructor }
cause
- the cause (which is saved for later retrieval by the
getCause()
method). (A
null
value is permitted, and indicates that the cause is nonexistent or unknown.)
Throwable
instance.
IllegalArgumentException
- if
cause
is this throwable. (A throwable cannot be its own cause.)
IllegalStateException
- if this throwable was created with
Throwable(Throwable)
or
Throwable(String,Throwable)
, or this method has already been called on this throwable.
public String toString()
getLocalizedMessage()
methodgetLocalizedMessage
returns
null
, then just the class name is returned.
toString
in class
Object
public void printStackTrace()
Throwable
object on the error output stream that is the value of the field
System.err
. The first line of output contains the result of the
toString()
method for this object. Remaining lines represent data previously recorded by the method
fillInStackTrace()
. The format of this information depends on the implementation, but the following example may be regarded as typical:
This example was produced by running the program:java.lang.NullPointerException at MyClass.mash(MyClass.java:9) at MyClass.crunch(MyClass.java:6) at MyClass.main(MyClass.java:3)
class MyClass { public static void main(String[] args) { crunch(null); } static void crunch(int[] a) { mash(a); } static void mash(int[] b) { System.out.println(b[0]); } }The backtrace for a throwable with an initialized, non-null cause should generally include the backtrace for the cause. The format of this information depends on the implementation, but the following example may be regarded as typical:
HighLevelException: MidLevelException: LowLevelException at Junk.a(Junk.java:13) at Junk.main(Junk.java:4) Caused by: MidLevelException: LowLevelException at Junk.c(Junk.java:23) at Junk.b(Junk.java:17) at Junk.a(Junk.java:11) ... 1 more Caused by: LowLevelException at Junk.e(Junk.java:30) at Junk.d(Junk.java:27) at Junk.c(Junk.java:21) ... 3 moreNote the presence of lines containing the characters
"..."
. These lines indicate that the remainder of the stack trace for this exception matches the indicated number of frames from the bottom of the stack trace of the exception that was caused by this exception (the "enclosing" exception). This shorthand can greatly reduce the length of the output in the common case where a wrapped exception is thrown from same method as the "causative exception" is caught. The above example was produced by running the program:
public class Junk { public static void main(String args[]) { try { a(); } catch(HighLevelException e) { e.printStackTrace(); } } static void a() throws HighLevelException { try { b(); } catch(MidLevelException e) { throw new HighLevelException(e); } } static void b() throws MidLevelException { c(); } static void c() throws MidLevelException { try { d(); } catch(LowLevelException e) { throw new MidLevelException(e); } } static void d() throws LowLevelException { e(); } static void e() throws LowLevelException { throw new LowLevelException(); } } class HighLevelException extends Exception { HighLevelException(Throwable cause) { super(cause); } } class MidLevelException extends Exception { MidLevelException(Throwable cause) { super(cause); } } class LowLevelException extends Exception { }As of release 7, the platform supports the notion of suppressed exceptions (in conjunction with the
try
-with-resources statement). Any exceptions that were suppressed in order to deliver an exception are printed out beneath the stack trace. The format of this information depends on the implementation, but the following example may be regarded as typical:
Exception in thread "main" java.lang.Exception: Something happened at Foo.bar(Foo.java:10) at Foo.main(Foo.java:5) Suppressed: Resource$CloseFailException: Resource ID = 0 at Resource.close(Resource.java:26) at Foo.bar(Foo.java:9) ... 1 moreNote that the "... n more" notation is used on suppressed exceptions just at it is used on causes. Unlike causes, suppressed exceptions are indented beyond their "containing exceptions."
An exception can have both a cause and one or more suppressed exceptions:
Exception in thread "main" java.lang.Exception: Main block at Foo3.main(Foo3.java:7) Suppressed: Resource$CloseFailException: Resource ID = 2 at Resource.close(Resource.java:26) at Foo3.main(Foo3.java:5) Suppressed: Resource$CloseFailException: Resource ID = 1 at Resource.close(Resource.java:26) at Foo3.main(Foo3.java:5) Caused by: java.lang.Exception: I did it at Foo3.main(Foo3.java:8)Likewise, a suppressed exception can have a cause:
Exception in thread "main" java.lang.Exception: Main block at Foo4.main(Foo4.java:6) Suppressed: Resource2$CloseFailException: Resource ID = 1 at Resource2.close(Resource2.java:20) at Foo4.main(Foo4.java:5) Caused by: java.lang.Exception: Rats, you caught me at Resource2$CloseFailException.(Resource2.java:45) ... 2 more
public void printStackTrace(PrintStream s)
s
-
PrintStream
to use for output
public void printStackTrace(PrintWriter s)
s
-
PrintWriter
to use for output
public Throwable fillInStackTrace()
Throwable
object information about the current state of the stack frames for the current thread.
If the stack trace of this Throwable
is not writable, calling this method has no effect.
Throwable
instance.
printStackTrace()
public StackTraceElement[] getStackTrace()
printStackTrace()
. Returns an array of stack trace elements, each representing one stack frame. The zeroth element of the array (assuming the array's length is non-zero) represents the top of the stack, which is the last method invocation in the sequence. Typically, this is the point at which this throwable was created and thrown. The last element of the array (assuming the array's length is non-zero) represents the bottom of the stack, which is the first method invocation in the sequence.
Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this throwable is permitted to return a zero-length array from this method. Generally speaking, the array returned by this method will contain one element for every frame that would be printed byprintStackTrace
. Writes to the returned array do not affect future calls to this method.
public void setStackTrace(StackTraceElement[] stackTrace)
getStackTrace()
and printed by
printStackTrace()
and related methods. This method, which is designed for use by RPC frameworks and other advanced systems, allows the client to override the default stack trace that is either generated by
fillInStackTrace()
when a throwable is constructed or deserialized when a throwable is read from a serialization stream.
If the stack trace of this Throwable
is not writable, calling this method has no effect other than validating its argument.
stackTrace
- the stack trace elements to be associated with this
Throwable
. The specified array is copied by this call; changes in the specified array after the method invocation returns will have no affect on this
Throwable
's stack trace.
NullPointerException
- if
stackTrace
is
null
or if any of the elements of
stackTrace
are
null
public final void addSuppressed(Throwable exception)
try
-with-resources statement.
The suppression behavior is enabled unless disabled via a constructor. When suppression is disabled, this method does nothing other than to validate its argument.
Note that when one exception causes another exception, the first exception is usually caught and then the second exception is thrown in response. In other words, there is a causal connection between the two exceptions. In contrast, there are situations where two independent exceptions can be thrown in sibling code blocks, in particular in the try
block of a try
-with-resources statement and the compiler-generated finally
block which closes the resource. In these situations, only one of the thrown exceptions can be propagated. In the try
-with-resources statement, when there are two such exceptions, the exception originating from the try
block is propagated and the exception from the finally
block is added to the list of exceptions suppressed by the exception from the try
block. As an exception unwinds the stack, it can accumulate multiple suppressed exceptions.
An exception may have suppressed exceptions while also being caused by another exception. Whether or not an exception has a cause is semantically known at the time of its creation, unlike whether or not an exception will suppress other exceptions which is typically only determined after an exception is thrown.
Note that programmer written code is also able to take advantage of calling this method in situations where there are multiple sibling exceptions and only one can be propagated.
exception
- the exception to be added to the list of suppressed exceptions
IllegalArgumentException
- if
exception
is this throwable; a throwable cannot suppress itself.
NullPointerException
- if
exception
is
null
public final Throwable[] getSuppressed()
try
-with-resources statement, in order to deliver this exception. If no exceptions were suppressed or suppression is disabled, an empty array is returned. This method is thread-safe. Writes to the returned array do not affect future calls to this method.
java.lang.Object
java.lang.Throwable
public class Throwable
Throwable
类是 Java 语言中所有错误或异常的超类。只有当对象是此类(或其子类之一)的实例时,才能通过 Java 虚拟机或者 Java throw
语句抛出。类似地,只有此类或其子类之一才可以是 catch
子句中的参数类型。
两个子类的实例,Error 和 Exception,通常用于指示发生了异常情况。通常,这些实例是在异常情况的上下文中新近创建的,因此包含了相关的信息(比如堆栈跟踪数据)。
Throwable 包含了其线程创建时线程执行堆栈的快照。它还包含了给出有关错误更多信息的消息字符串。最后,它还可以包含 cause(原因):另一个导致此 throwable 抛出的 throwable。此 cause 设施在 1.4 版本中首次出现。它也称为异常链 设施,因为 cause 自身也会有 cause,依此类推,就形成了异常链,每个异常都是由另一个异常引起的。
导致 throwable cause 的一个理由是,抛出它的类构建在低层抽象之中,而高层操作由于低层操作的失败而失败。让低层抛出的 throwable 向外传播是一种糟糕的设计方法,因为它通常与高层提供的抽象不相关。此外,这样做将高层 API 与其实现细节关联起来,假定低层异常是经过检查的异常。抛出“经过包装的异常”(即包含 cause 的异常)允许高层与其调用方交流失败详细信息,而不会招致上述任何一个缺点。这种方式保留了改变高层实现而不改变其 API 的灵活性(尤其是,异常集合通过其方法抛出)。
导致 throwable cause 的另一个 cause 是,抛出它的方法必须符合通用接口,而通用接口不允许方法直接抛出 cause。例如,假定持久集合符合 Collection 接口,而其持久性在 java.io 的基础上实现。假定 add 方法的内部可以抛出 IOException。实现可以与其调用方交流 IOException 的详细消息,同时通过以一种合适的未检查的异常来包装 IOException,使其符合 Collection 接口。(持久集合的规范应该指示它能够抛出这种异常。)
Cause 可以通过两种方式与 throwable 关联起来:通过一个将 cause 看作参数的构造方法;或者通过 initCause(Throwable) 方法。对于那些希望将 cause 与其关联起来的新 throwable 类,应该提供带有 cause 的构造方法,并委托(可能间接)给一个带有 cause 的 Throwable 构造方法。例如:
try { lowLevelOp(); } catch (LowLevelException le) { throw new HighLevelException(le); // Chaining-aware constructor }因为 initCause 方法是公共的,它允许 cause 与任何 throwable 相关联,甚至包括“遗留 throwable”,它的实现提前将异常链机制的附件应用到 Throwable。例如:
try { lowLevelOp(); } catch (LowLevelException le) { throw (HighLevelException) new HighLevelException().initCause(le); // Legacy constructor }
在版本 1.4 之前,许多 throwable 有自己的非标准异常链机制( ExceptionInInitializerError、 ClassNotFoundException、 UndeclaredThrowableException、 InvocationTargetException、 WriteAbortedException、 PrivilegedActionException、 PrinterIOException、 RemoteException 和 NamingException)。所有这些 throwable 都已经更新过,可以使用标准异常链机制,同时继续实现其“遗留”链机制,以保持兼容性。
此外,从版本 1.4 开始,许多通用的 Throwable 类(例如,Exception、RuntimeException、Error)都已经更新,具有带 cause 的构造方法。由于有 initCause 方法存在,这不是严格要求的,但它更方便,也更形象地委托给一个带有 cause 的构造方法。
根据惯例,Throwable
类及其子类有两个构造方法,一个不带参数,另一个带有 String
参数,此参数可用于生成详细消息。此外,这些子类很可能有与其相关联的 cause,因此也应有两个构造方法,一个带 Throwable
(cause),一个带 String
(详细消息)和 Throwable
(cause)。
在版本 1.4 中还引入了 getStackTrace() 方法,它允许通过各种形式的 printStackTrace() 方法编程访问堆栈跟踪信息,这些信息以前只能以文本形式使用。此信息已经添加到该类的序列化表示形式,因此 getStackTrace 和 printStackTrace 将可在反序列化时获得的 throwable 上正确操作。
构造方法摘要 | |
---|---|
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。 |
方法摘要 | |
---|---|
Throwable |
fillInStackTrace() 在异常堆栈跟踪中填充。 |
Throwable |
getCause() 返回此 throwable 的 cause;如果 cause 不存在或未知,则返回 null 。 |
String |
getLocalizedMessage() 创建此 throwable 的本地化描述。 |
String |
getMessage() 返回此 throwable 的详细消息字符串。 |
StackTraceElement[] |
getStackTrace() 提供编程访问由 printStackTrace() 输出的堆栈跟踪信息。 |
Throwable |
initCause(Throwable cause) 将此 throwable 的 cause 初始化为指定值。 |
void |
printStackTrace() 将此 throwable 及其追踪输出至标准错误流。 |
void |
printStackTrace(PrintStream s) 将此 throwable 及其追踪输出到指定的输出流。 |
void |
printStackTrace(PrintWriter s) 将此 throwable 及其追踪输出到指定的 PrintWriter。 |
void |
setStackTrace(StackTraceElement[] stackTrace) 设置将由 getStackTrace() 返回,并由 printStackTrace() 和相关方法输出的堆栈跟踪元素。 |
String |
toString() 返回此 throwable 的简短描述。 |
从类 java.lang.Object 继承的方法 |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
构造方法详细信息 |
---|
public Throwable()
null
作为其详细消息的新 throwable。Cause 尚未进行初始化,可在以后通过调用 initCause(java.lang.Throwable) 来初始化。
调用 fillInStackTrace() 方法来初始化新创建的 throwable 中的堆栈跟踪数据。
public Throwable(String message)
调用 fillInStackTrace() 方法来初始化新创建的 throwable 中的堆栈跟踪数据。
message
- 详细消息。保存这个详细消息,以便以后通过 getMessage() 方法对其进行获取。
public Throwable(String message,
Throwable cause)
注意,与 cause
相关的详细消息不是 自动合并到这个 throwable 的详细消息中的。
调用 fillInStackTrace() 方法来初始化新创建的 throwable 中的堆栈跟踪数据。
message
- 详细消息(保存此消息,以便以后通过 getMessage() 方法获取它)。
cause
- 原因(保存此 cause,以便以后通过 getCause() 方法获取它)。(允许
null 值,指出 cause 是不存在的或是未知的。)
public Throwable(Throwable cause)
调用 fillInStackTrace() 方法来初始化新创建的 throwable 中的堆栈跟踪数据。
cause
- 原因(保存此 cause,以便以后通过 getCause() 方法获取它)。(允许
null 值,指出 cause 是不存在的或是未知的。)
方法详细信息 |
---|
public String getMessage()
public String getLocalizedMessage()
getMessage()
相同的结果。
public Throwable getCause()
null
。(该 Cause 是导致抛出此 throwable 的throwable。)
此实现返回由一个需要 Throwable 的构造方法提供的 cause,或者在创建之后通过 initCause(Throwable) 方法进行设置的 cause。虽然通常不需要重写此方法,但子类可以重写它,以返回一个通过某些其他方式设置的 cause。这适用于在异常链(异常嵌套)机制被加入到 Throwable 之前存在“遗留 Throwable 链机制”的情况。注意,不必 重写任何 PrintStackTrace 方法,所有方法都调用 getCause 方法来确定 throwable 的 cause。
null
。
public Throwable initCause(Throwable cause)
此方法至多可以调用一次。此方法通常从构造方法中调用,或者在创建 throwable 后立即调用。如果此 throwable 通过 Throwable(Throwable) 或 Throwable(String,Throwable) 创建,此方法甚至一次也不能调用。
cause
- 原因(保存此 cause,以便以后通过 getCause() 方法获取它)。(允许
null 值,指出 cause 是不存在的或是未知的。)
Throwable
实例的引用。
IllegalArgumentException
- 如果
cause
是此 throwable。(throwable 不能是它自己的 cause。)
IllegalStateException
- 如果此 throwable 通过 Throwable(Throwable) 或 Throwable(String,Throwable) 创建,或者此方法已经在此 throwable 上进行调用。
public String toString()
Object
中的
toString
public void printStackTrace()
Throwable
对象的堆栈跟踪输出至错误输出流,作为字段
System.err
的值。输出的第一行包含此对象的 toString() 方法的结果。剩余行表示以前由方法 fillInStackTrace() 记录的数据。此信息的格式取决于实现,但以下示例是最常见的:
本示例通过运行以下程序生成:java.lang.NullPointerException at MyClass.mash(MyClass.java:9) at MyClass.crunch(MyClass.java:6) at MyClass.main(MyClass.java:3)
class MyClass { public static void main(String[] args) { crunch(null); } static void crunch(int[] a) { mash(a); } static void mash(int[] b) { System.out.println(b[0]); } }对于带初始化非空 cause 的 throwable 的追踪,通常应该包括 cause 的追踪。此信息的格式取决于实现,但以下示例是最常见的:
HighLevelException: MidLevelException: LowLevelException at Junk.a(Junk.java:13) at Junk.main(Junk.java:4) Caused by: MidLevelException: LowLevelException at Junk.c(Junk.java:23) at Junk.b(Junk.java:17) at Junk.a(Junk.java:11) ... 1 more Caused by: LowLevelException at Junk.e(Junk.java:30) at Junk.d(Junk.java:27) at Junk.c(Junk.java:21) ... 3 more注意,存在包含字符 "..." 的行。这些行指示此异常的椎栈跟踪的其余部分匹配来自异常(由 "enclosing" 异常引起)的堆栈跟踪底部的指定数量的帧。这种简便方法可以大大缩短通常情况下的输出长度,这里抛出了包装的异常,其方法与捕获“作为 cause 的异常”的方法相同。上述示例通过运行以下程序生成:
public class Junk { public static void main(String args[]) { try { a(); } catch(HighLevelException e) { e.printStackTrace(); } } static void a() throws HighLevelException { try { b(); } catch(MidLevelException e) { throw new HighLevelException(e); } } static void b() throws MidLevelException { c(); } static void c() throws MidLevelException { try { d(); } catch(LowLevelException e) { throw new MidLevelException(e); } } static void d() throws LowLevelException { e(); } static void e() throws LowLevelException { throw new LowLevelException(); } } class HighLevelException extends Exception { HighLevelException(Throwable cause) { super(cause); } } class MidLevelException extends Exception { MidLevelException(Throwable cause) { super(cause); } } class LowLevelException extends Exception { }
public void printStackTrace(PrintStream s)
s
- 用于输出的
PrintStream
public void printStackTrace(PrintWriter s)
s
- 用于输出的
PrintWriter
public Throwable fillInStackTrace()
Throwable
对象信息中记录有关当前线程堆栈帧的当前状态。
Throwable
实例的引用。
public StackTraceElement[] getStackTrace()
某些虚拟机在某些情况下可能会从堆栈跟踪中省略一个或多个堆栈帧。在极端情况下,没有该 throwable 堆栈跟踪信息的虚拟机可以从该方法返回一个零长度数组。一般说来,由此方法返回的数组将包含由 printStackTrace 输出的每帧的一个元素。
public void setStackTrace(StackTraceElement[] stackTrace)
stackTrace
- 要与此
Throwable
关联的堆栈跟踪元素。指定的数组由此调用复制;在方法调用返回后,指定数组中的改变将不会对此
Throwable
的堆栈跟踪产生影响。
NullPointerException
- 如果
stackTrace
为
null
,或者
stackTrace
中的任何元素为
null