Class SafeException

All Implemented Interfaces:
Serializable

public class SafeException extends RuntimeException
A runtime exception wrapper for checked exceptions.

SafeException provides a way to wrap checked exceptions as unchecked exceptions, enabling cleaner functional code without excessive try-catch blocks. It is the standard exception type thrown by the CoreFun library when operations fail.

Design Philosophy

Java's checked exceptions force explicit handling at every call site, which conflicts with functional programming patterns like streams and lambdas. SafeException bridges this gap by allowing checked exceptions to propagate as unchecked exceptions while preserving the original cause for debugging.

When to Use

  • Wrapping checked exceptions in lambda expressions
  • Converting library exceptions to application-level exceptions
  • Providing context messages while preserving the original cause

Example Usage


 // Manual wrapping with context
 try {
     riskyOperation();
 } catch (IOException e) {
     throw new SafeException("Failed to read file: " + path, e);
 }

 // Using the static wrap method (preserves RuntimeExceptions)
 try {
     operation();
 } catch (Exception e) {
     throw SafeException.wrap(e);  // Returns original if already RuntimeException
 }

 // Adding context to any exception
 throw SafeException.wrap("Database query failed", e);
 
Since:
0.1.0
Author:
Guinetik <guinetik@gmail.com>
See Also:
  • Constructor Details

    • SafeException

      public SafeException(Throwable cause)
      Creates a SafeException wrapping the given cause.
      Parameters:
      cause - the underlying exception
    • SafeException

      public SafeException(String message, Throwable cause)
      Creates a SafeException with a message and cause.
      Parameters:
      message - descriptive message about the error context
      cause - the underlying exception
    • SafeException

      public SafeException(String message)
      Creates a SafeException with just a message.
      Parameters:
      message - descriptive message about the error
  • Method Details

    • wrap

      public static RuntimeException wrap(Exception e)
      Wraps a checked exception as a SafeException. If the exception is already a RuntimeException, it is returned as-is.
      Parameters:
      e - the exception to wrap
      Returns:
      a RuntimeException (either the original or wrapped)
    • wrap

      public static SafeException wrap(String message, Exception e)
      Wraps a checked exception with a descriptive message.
      Parameters:
      message - context description
      e - the exception to wrap
      Returns:
      a SafeException wrapping the original