Java : Throwable con ejemplos
Throwable (Java SE 22 & JDK 22) en Java con ejemplos.
Encontrará ejemplos de código en la mayoría de los métodos de Throwable.
Nota :
- Este artículo puede utilizar software de traducción para su comodidad. Consulte también la versión original en inglés.
Summary
La clase Throwable es la superclase de todos los errores y excepciones en el lenguaje Java. Sólo los objetos que son instancias de esta clase (o una de sus subclases) son lanzados por la máquina virtual Java o pueden ser lanzados por la declaración de lanzamiento de Java. (Traducción automática)
Code examples on this page uses the SampleException class below.
@SuppressWarnings("serial")
public class SampleException extends Exception {
public SampleException() {
}
public SampleException(String message) {
super(message);
}
public SampleException(String message, Throwable cause) {
super(message, cause);
}
public SampleException(Throwable cause) {
super(cause);
}
public SampleException(String message, Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
public class Main {
public static void main(String[] args) {
try {
func1();
} catch (SampleException e) {
final Throwable t = e;
t.printStackTrace();
// Result
// ↓
// SampleException
// Main.func2 ...
// Main.func1 ...
// Main.main ...
// ...
}
}
private static void func1() throws SampleException {
func2();
}
private static void func2() throws SampleException {
throw new SampleException();
}
}
Constructors
Throwable ()
Construye un nuevo arrojable con nulo como mensaje detallado. (Traducción automática)
final Throwable t = new SampleException();
System.out.println(t); // SampleException
Throwable (String message)
Construye un nuevo elemento arrojable con el mensaje detallado especificado. (Traducción automática)
final Throwable t = new SampleException("abcde");
System.out.println(t); // SampleException: abcde
System.out.println(t.getMessage()); // abcde
Throwable (String message, Throwable cause)
Construye un nuevo elemento arrojable con el mensaje detallado y la causa especificados. (Traducción automática)
final Throwable cause = new SampleException("XYZ");
final Throwable t = new SampleException("abcde", cause);
System.out.println(t); // SampleException: abcde
System.out.println(t.getMessage()); // abcde
System.out.println(t.getCause()); // SampleException: XYZ
System.out.println(t.getCause().getMessage()); // XYZ
Throwable (String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)
Construye un nuevo elemento arrojable con el mensaje detallado especificado, la causa, la supresión habilitada o deshabilitada y el seguimiento de pila grabable habilitado o deshabilitado. (Traducción automática)
final Throwable cause = new SampleException("XYZ");
final Throwable t = new SampleException("abcde", cause, true, true);
System.out.println(t); // SampleException: abcde
System.out.println(t.getCause()); // SampleException: XYZ
t.addSuppressed(new SampleException("E1"));
t.addSuppressed(new SampleException("E2"));
// [SampleException: E1, SampleException: E2]
System.out.println(Arrays.toString(t.getSuppressed()));
System.out.println(t.getStackTrace().length > 0); // true
// enableSuppression = false
final Throwable cause = new SampleException("XYZ");
final Throwable t = new SampleException("abcde", cause, false, true);
System.out.println(t); // SampleException: abcde
System.out.println(t.getCause()); // SampleException: XYZ
t.addSuppressed(new SampleException("E1"));
t.addSuppressed(new SampleException("E2"));
System.out.println(Arrays.toString(t.getSuppressed())); // []
System.out.println(t.getStackTrace().length > 0); // true
// writableStackTrace = false
final Throwable cause = new SampleException("XYZ");
final Throwable t = new SampleException("abcde", cause, true, false);
System.out.println(t); // SampleException: abcde
System.out.println(t.getCause()); // SampleException: XYZ
t.addSuppressed(new SampleException("E1"));
t.addSuppressed(new SampleException("E2"));
// [SampleException: E1, SampleException: E2]
System.out.println(Arrays.toString(t.getSuppressed()));
System.out.println(t.getStackTrace().length); // 0
Throwable (Throwable cause)
Construye un nuevo elemento arrojable con la causa especificada y un mensaje detallado de (cause==null ? null : cause.toString()) (que normalmente contiene la clase y el mensaje detallado de la causa). (Traducción automática)
final Throwable cause = new SampleException("XYZ");
final Throwable t = new SampleException(cause);
System.out.println(t); // SampleException: SampleException: XYZ
System.out.println(t.getMessage()); // SampleException: XYZ
System.out.println(t.getCause()); // SampleException: XYZ
System.out.println(t.getCause().getMessage()); // XYZ
Methods
final void addSuppressed (Throwable exception)
Agrega la excepción especificada a las excepciones que se suprimieron para entregar esta excepción. (Traducción automática)
final Throwable t = new SampleException("abcd");
System.out.println(t); // SampleException: abcd
t.addSuppressed(new SampleException("E1"));
t.addSuppressed(new SampleException("E2"));
final var ret = t.getSuppressed();
System.out.println(Arrays.toString(ret)); // [SampleException: E1, SampleException: E2]
Throwable fillInStackTrace ()
Completa el seguimiento de la pila de ejecución. (Traducción automática)
public class Main {
public static void main(String[] args) {
try {
func1();
} catch (SampleException e) {
final Throwable t = e;
System.out.println("-- getStackTrace --");
for (final var element : t.getStackTrace()) {
System.out.println(element);
}
// Result
// ↓
//-- getStackTrace --
// Main.func2 ...
// Main.func1 ...
// Main.main ...
// ...
// The stack trace is overwritten.
final var ret = t.fillInStackTrace();
System.out.println(ret); // SampleException
System.out.println("-- getStackTrace --");
for (final var element : t.getStackTrace()) {
System.out.println(element);
}
// Result
// ↓
//-- getStackTrace --
// Main.main ...
// ...
}
}
private static void func1() throws SampleException {
func2();
}
private static void func2() throws SampleException {
throw new SampleException();
}
}
Throwable getCause ()
Devuelve la causa de este arrojable o nulo si la causa es inexistente o desconocida. (Traducción automática)
final Throwable t = new SampleException();
System.out.println(t); // SampleException
System.out.println(t.getCause()); // null
final Throwable cause = new SampleException("XYZ");
final Throwable t = new SampleException(cause);
System.out.println(t); // SampleException: SampleException: XYZ
System.out.println(t.getCause()); // SampleException: XYZ
System.out.println(t.getCause().getMessage()); // XYZ
String getLocalizedMessage ()
Crea una descripción localizada de este arrojable. (Traducción automática)
@SuppressWarnings("serial")
class LocalizedException extends Exception {
private final static String MESSAGE_EN = "Exception! (EN)";
private final static String MESSAGE_JA = "Exception! (JA)";
LocalizedException() {
super(MESSAGE_EN);
}
@Override
public String getLocalizedMessage() {
// It is a simple implementation.
final var locale = Locale.getDefault();
return switch (locale.getLanguage()) {
case "ja" -> MESSAGE_JA;
default -> MESSAGE_EN;
};
}
}
{
System.out.println(Locale.getDefault().toLanguageTag()); // en-US
final Throwable t = new LocalizedException();
System.out.println(t); // LocalizedException: Exception! (EN)
System.out.println(t.getMessage()); // Exception! (EN)
System.out.println(t.getLocalizedMessage()); // Exception! (EN)
}
{
Locale.setDefault(Locale.JAPAN);
System.out.println(Locale.getDefault().toLanguageTag()); // ja-JP
final Throwable t = new LocalizedException();
System.out.println(t); // LocalizedException: Exception! (JA)
System.out.println(t.getMessage()); // Exception! (EN)
System.out.println(t.getLocalizedMessage()); // Exception! (JA)
}
String getMessage ()
Devuelve la cadena de mensaje detallada de este arrojable. (Traducción automática)
final Throwable t = new SampleException("abcd");
System.out.println(t); // SampleException: abcd
System.out.println(t.getMessage()); // abcd
StackTraceElement[] getStackTrace ()
Proporciona acceso programático a la información de seguimiento de la pila impresa por printStackTrace(). (Traducción automática)
public class Main {
public static void main(String[] args) {
try {
func1();
} catch (SampleException e) {
final Throwable t = e;
System.out.println("-- getStackTrace --");
for (final var element : t.getStackTrace()) {
System.out.println(element);
}
// Result
// ↓
//-- getStackTrace --
// Main.func2 ...
// Main.func1 ...
// Main.main ...
// ...
}
}
private static void func1() throws SampleException {
func2();
}
private static void func2() throws SampleException {
throw new SampleException();
}
}
final Throwable[] getSuppressed ()
Devuelve una matriz que contiene todas las excepciones que fueron suprimidas, generalmente mediante la declaración try-with-resources, para entregar esta excepción. (Traducción automática)
final Throwable t = new SampleException("abcd");
System.out.println(t); // SampleException: abcd
t.addSuppressed(new SampleException("E1"));
t.addSuppressed(new SampleException("E2"));
final var ret = t.getSuppressed();
System.out.println(Arrays.toString(ret)); // [SampleException: E1, SampleException: E2]
Throwable initCause (Throwable cause)
Inicializa la causa de este arrojable al valor especificado. (Traducción automática)
final Throwable t = new SampleException();
System.out.println(t); // SampleException
System.out.println(t.getCause()); // null
final Throwable cause = new SampleException("XYZ");
System.out.println(t.initCause(cause)); // SampleException
System.out.println(t.getCause()); // SampleException: XYZ
void printStackTrace ()
Imprime este elemento arrojable y su seguimiento al flujo de error estándar. (Traducción automática)
public class Main {
public static void main(String[] args) {
try {
func1();
} catch (SampleException e) {
final Throwable t = e;
t.printStackTrace();
// Result
// ↓
// SampleException
// Main.func2 ...
// Main.func1 ...
// Main.main ...
// ...
}
}
private static void func1() throws SampleException {
func2();
}
private static void func2() throws SampleException {
throw new SampleException();
}
}
void printStackTrace (PrintStream s)
Imprime este elemento desechable y su rastreo hacia el flujo de impresión especificado. (Traducción automática)
public class Main {
public static void main(String[] args) throws IOException {
try {
func1();
} catch (SampleException e) {
final Throwable t = e;
final var path = Path.of("R:", "java-work", "aaa.txt");
try (final var s = new PrintStream(Files.newOutputStream(path))) {
t.printStackTrace(s);
}
System.out.println("-- readString --");
System.out.println(Files.readString(path));
// Result
// ↓
//-- readString --
// SampleException
// Main.func2 ...
// Main.func1 ...
// Main.main ...
// ...
}
}
private static void func1() throws SampleException {
func2();
}
private static void func2() throws SampleException {
throw new SampleException();
}
}
void printStackTrace (PrintWriter s)
Imprime este elemento desechable y su rastreo hasta el escritor de impresión especificado. (Traducción automática)
public class Main {
public static void main(String[] args) throws IOException {
try {
func1();
} catch (SampleException e) {
final Throwable t = e;
final var stringWriter = new StringWriter();
try (final var printWriter = new PrintWriter(stringWriter)) {
t.printStackTrace(printWriter);
}
System.out.println("-- StringWriter --");
System.out.println(stringWriter);
// Result
// ↓
//-- StringWriter --
// SampleException
// Main.func2 ...
// Main.func1 ...
// Main.main ...
// ...
}
}
private static void func1() throws SampleException {
func2();
}
private static void func2() throws SampleException {
throw new SampleException();
}
}
void setStackTrace (StackTraceElement[] stackTrace)
Establece los elementos de seguimiento de la pila que getStackTrace() devolverá e imprimirá mediante printStackTrace() y métodos relacionados. (Traducción automática)
final Throwable t = new SampleException();
final var elements = List.of(
new StackTraceElement("ClassA", "methodB", "FileC.java", 123),
new StackTraceElement("ClassX", "methodY", "FileZ.java", 456)
);
t.setStackTrace(elements.toArray(new StackTraceElement[0]));
t.printStackTrace();
// Result
// ↓
//SampleException
// at ClassA.methodB(FileC.java:123)
// at ClassX.methodY(FileZ.java:456)
String toString ()
Devuelve una breve descripción de este arrojable. (Traducción automática)
final Throwable t = new SampleException("abcde");
final var str = t.toString();
System.out.println(str); // SampleException: abcde
Related posts
- Ejemplos de API