Class ThrowableUtils

java.lang.Object
org.apache.juneau.commons.utils.ThrowableUtils

public class ThrowableUtils extends Object
Various utility methods for working with throwables.

Exception factory methods (terse rex/brex/iaex/isex/uoex/ uoroex/ioex/exex constructors) live on Shorts and construct their exceptions directly with no side-effects. This class retains only throwable inspection/handling helpers (stack-trace rendering, cause walking, safe-run wrappers, casting).

The opt-in log(Throwable) helper checks the juneau.enableVerboseExceptions setting and, when enabled, prints the throwable's stack trace to the logger. It is not invoked automatically by any factory — callers that want verbose logging at a specific site must call it explicitly.

Example — enabling for a single test thread:

Settings.get().setLocal("juneau.enableVerboseExceptions", "true"); try { // ... code under test ... } finally { Settings.get().clearLocal(); }

See Also:
  • Constructor Details

  • Method Details

    • castException

      public static <T> T castException(Class<T> type, Throwable t)
      Casts or wraps the specified throwable to the specified type.
      Type Parameters:
      T - The class to cast to.
      Parameters:
      type - The class to cast to. Must not be null.
      t - The throwable to cast. Can be null (produces a wrapper with a null cause).
      Returns:
      Either the same exception if it's already the specified type, or a wrapped exception.
    • findCause

      public static <T extends Throwable> Optional<T> findCause(Throwable e, Class<T> cause)
      Searches through the cause chain of an exception to find an exception of the specified type.
      Type Parameters:
      T - The cause type.
      Parameters:
      e - The exception to search. Can be null (returns an empty Optional).
      cause - The cause type to search for. Must not be null.
      Returns:
      An Optional containing the cause if found, or empty if not found.
    • getStackTrace

      public static String getStackTrace(Throwable t)
      Convenience method for getting a stack trace as a string.
      Parameters:
      t - The throwable to get the stack trace from. Must not be null.
      Returns:
      The same content that would normally be rendered via t.printStackTrace()
    • printStackTrace

      public static void printStackTrace(Throwable t, PrintWriter pw, Integer maxDepth)
      Prints a stack trace with a maximum depth limit.

      This method is useful for StackOverflowError situations where printing the full stack trace can cause additional errors due to stack exhaustion. The stack trace will be limited to the specified maximum number of elements.

      Example:

      try { // Some code that might cause StackOverflowError } catch (StackOverflowError e) { // Print only first 100 stack trace elements ThrowableUtils.printStackTrace(e, System.err, 100); }

      Parameters:
      t - The throwable to print the stack trace for. Must not be null.
      pw - The print writer to write to. Must not be null.
      maxDepth - The maximum number of stack trace elements to print. If null or negative, prints all elements.
    • printStackTrace

      public static void printStackTrace(Throwable t, Integer maxDepth)
      Prints a stack trace with a maximum depth limit to standard error.

      This method is useful for StackOverflowError situations where printing the full stack trace can cause additional errors due to stack exhaustion. The stack trace will be limited to the specified maximum number of elements.

      Same as printStackTrace(Throwable, PrintWriter, Integer) but writes to System.err.

      Example:

      try { // Some code that might cause StackOverflowError } catch (StackOverflowError e) { // Print only first 100 stack trace elements to stderr ThrowableUtils.printStackTrace(e, 100); }

      Parameters:
      t - The throwable to print the stack trace for.
      maxDepth - The maximum number of stack trace elements to print. If null or negative, prints all elements.
    • getThrowableCause

      public static <T extends Throwable> T getThrowableCause(Class<T> c, Throwable t)
      Same as Throwable.getCause() but searches the throwable chain for an exception of the specified type.
      Type Parameters:
      T - The throwable type to search for.
      Parameters:
      c - The throwable type to search for. Must not be null.
      t - The throwable to search. Can be null (returns null).
      Returns:
      The exception, or null if not found.
    • hash

      public static int hash(Throwable t, String stopClass)
      Calculates a 16-bit hash for the specified throwable based on it's stack trace.
      Parameters:
      t - The throwable to calculate the stack trace on. Can be null (returns 0).
      stopClass - Optional stop class on which to stop calculation of a stack trace beyond when found. Can be null (the entire stack trace, including causes, is used).
      Returns:
      A calculated hash.
    • log

      public static <T extends Throwable> T log(T exception)
      Opt-in verbose logger for a throwable.

      When the juneau.enableVerboseExceptions setting is true, logs the throwable's stack trace as a warning; otherwise does nothing. Returns the same throwable to allow inline use (e.g. throw log(iaex("..."))). This is never invoked automatically — call it explicitly at sites where verbose logging is desired.

      Type Parameters:
      T - The throwable type.
      Parameters:
      exception - The throwable to (optionally) log. Must not be null when verbose exceptions are enabled; otherwise returned unchanged (may be null).
      Returns:
      The same throwable.
    • localizedMessage

      public static String localizedMessage(Throwable t)
      Convenience method for calling Throwable.getLocalizedMessage().

      Long messages (>2000 characters) are truncated to prevent stack overflow issues when exception messages contain circular references. The format is: "first-1000-chars<truncated-#-chars>last-1000-chars"

      Parameters:
      t - The throwable. Must not be null.
      Returns:
      The localized message of the throwable, truncated if necessary, or null if the throwable has no localized message.
    • toRuntimeException

      Wraps or casts to RuntimeException.
      A null argument produces a RuntimeException with a null cause.
    • toRex

      public static RuntimeException toRex(Throwable cause)
      Creates a new RuntimeException from the specified cause (or returns it if already one).
      Parameters:
      cause - The caused-by exception. Can be null (produces a RuntimeException with a null cause).
      Returns:
      A new RuntimeException, or the same exception if it's already of that type.
    • safe

      public static void safe(Snippet snippet)
      Runs a snippet; wraps any checked throwable in RuntimeException.
    • safe

      public static void safe(Snippet snippet, Function<Throwable,RuntimeException> exceptionMapper)
      Runs a snippet; maps any checked throwable via the provided function.
    • safe

      public static <T> T safe(ThrowingSupplier<T> s)
      Executes a supplier; wraps any checked exception in RuntimeException.
    • safe

      public static <T> T safe(ThrowingSupplier<T> s, Function<Throwable,RuntimeException> exceptionMapper)
      Executes a supplier; maps any checked exception via the provided function.
    • runQuietly

      public static void runQuietly(Snippet snippet)
      Runs a snippet, silently ignoring any exception.
    • safeCatch

      public static <T> T safeCatch(ThrowingSupplier<T> s, Function<Throwable,T> exceptionFunction)
      Executes a supplier; returns the result or a fallback value produced by the exception function.
    • safeOpt

      public static <T> Optional<T> safeOpt(ThrowingSupplier<T> s)
      Executes a supplier; returns an Optional of the result, or empty if an exception is thrown.
    • safeOptCatch

      public static <T> Optional<T> safeOptCatch(ThrowingSupplier<T> s, Function<Throwable,T> exceptionFunction)
      Executes a supplier; returns an Optional of the result or the exception function's value.
    • safeOrNull

      public static <T> T safeOrNull(ThrowingSupplier<T> s)
      Executes a supplier; returns the result or null if an exception is thrown.
    • safeSupplier

      public static <T> T safeSupplier(ThrowableUtils.SupplierWithThrowable<T> supplier)
      Executes a ThrowableUtils.SupplierWithThrowable; wraps any checked throwable in RuntimeException.
    • safeSupplier

      public static <T> T safeSupplier(ThrowableUtils.SupplierWithThrowable<T> supplier, Function<Throwable,RuntimeException> exceptionMapper)
      Executes a ThrowableUtils.SupplierWithThrowable; maps any checked throwable via the provided function.