Interface Snippet


public interface Snippet
A functional interface identical to Runnable but allows the run() method to throw checked exceptions.

This interface is useful when you need to pass arbitrary code snippets to methods that expect a Runnable, but your code may throw checked exceptions. Unlike Runnable, the run() method can throw any Throwable, making it suitable for exception testing and fluent API patterns.

Features:
  • Functional interface - can be used with lambda expressions and method references
  • Exception support - allows checked exceptions to be thrown
  • Fluent API friendly - enables passing code snippets in method chains
  • Testing support - useful for exception testing scenarios
Use Cases:
  • Exception testing - verifying that code throws expected exceptions
  • Fluent interfaces - passing code snippets to builder methods
  • Conditional execution - wrapping code that may throw exceptions
  • Error handling - passing error-prone code to handlers
Usage:

// Exception testing Snippet code = () -> { throw new IllegalArgumentException("Expected error"); }; assertThrown(IllegalArgumentException.class, code); // Fluent API usage builder .setValue("test") .onError(() -> { throw new ValidationException("Invalid value"); }) .build(); // Conditional execution with exceptions if (shouldExecute) { executeSafely(() -> { throw new IOException("File not found"); }); }

Comparison with Runnable:
  • Runnable: Cannot throw checked exceptions (must catch and wrap)
  • Snippet: Can throw any Throwable (checked or unchecked)
  • Runnable: Used for standard Java concurrency patterns
  • Snippet: Used for exception testing and fluent APIs
See Also:
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    run()
    Executes arbitrary code and optionally throws an exception.
  • Method Details

    • run

      void run() throws Throwable
      Executes arbitrary code and optionally throws an exception.

      This method is the functional method of this interface. It can throw any Throwable, including checked exceptions, which distinguishes it from Runnable.run().

      Example:

      Snippet snippet = () -> { // Code that may throw exceptions if (invalid) { throw new IllegalArgumentException("Invalid state"); } }; snippet.run(); // May throw IllegalArgumentException

      Throws:
      Throwable - Any throwable (checked or unchecked).