Interface SafeRunnable

Functional Interface:
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

@FunctionalInterface public interface SafeRunnable
A functional interface for operations that may throw checked exceptions.

SafeRunnable allows writing lambda expressions for operations that throw checked exceptions, which can then be converted to standard Runnable instances with automatic exception wrapping. This eliminates the boilerplate of try-catch blocks in lambda expressions.

Problem Solved

Java's Runnable interface declares void run() without any checked exceptions. This makes it impossible to use lambdas that throw checked exceptions directly with executors or other APIs expecting Runnable.

Example Usage


 // Define an operation that throws checked exceptions
 SafeRunnable task = () -> {
     Files.delete(path);  // throws IOException
 };

 // Convert to standard Runnable for use with executors
 executor.execute(task.toRunnable());

 // Or execute immediately with automatic wrapping
 task.execute();  // throws SafeException on failure

 // Create from existing Runnable
 SafeRunnable fromRunnable = SafeRunnable.from(() -> doSomething());
 
Since:
0.1.0
Author:
Guinetik <guinetik@gmail.com>
See Also:
  • Method Summary

    Modifier and Type
    Method
    Description
    default void
    Executes this SafeRunnable, wrapping any exception.
    from(Runnable runnable)
    Creates a SafeRunnable from a standard Runnable.
    void
    run()
    Executes the operation, potentially throwing a checked exception.
    default Runnable
    Converts this SafeRunnable to a standard Runnable.
  • Method Details

    • run

      void run() throws Exception
      Executes the operation, potentially throwing a checked exception.
      Throws:
      Exception - if the operation fails
    • toRunnable

      default Runnable toRunnable()
      Converts this SafeRunnable to a standard Runnable. Any checked exceptions are wrapped in SafeException.
      Returns:
      a Runnable that wraps checked exceptions
    • from

      static SafeRunnable from(Runnable runnable)
      Creates a SafeRunnable from a standard Runnable.
      Parameters:
      runnable - the Runnable to wrap
      Returns:
      a SafeRunnable that delegates to the Runnable
    • execute

      default void execute()
      Executes this SafeRunnable, wrapping any exception. Convenience method for immediate execution.
      Throws:
      SafeException - if execution fails