HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavaMinor

Providing unchecked exception "wrapper" interfaces for an API with checked exceptions

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
exceptionsexceptionwithprovidingwrapperforinterfacescheckedapiunchecked

Problem

I recently had a discussion in the forum of an API, because they changed an exception from checked to unchecked. I believed it needs to be checked, because it is recoverable. The arguments of "the other side" were verbosity and tediousness of try/catch or throws.

If it were purely theoretical question, I'd be right, but I agree that in practice it is sometimes tedious to write all these try/catches just for the sake of rethrowing unchecked exceptions, or logging.

So, an idea came to my mind, and I wonder whether it's viable. I'll illustrate with simple code:

public interface Foo {
    String foo() throws Exception;
}

public interface EasyFoo extends Foo {
    String foo();
}


These are two interfaces that define the same method (and this is enforced by inheritance), but the "easy" version does not define throwing checked exceptions. Then come 2 default implementations:

public class FooImpl implements Foo {

    @Override
    public String foo() throws Exception {
        return "foo";
    }
}

public class EasyFooImpl implements EasyFoo {

    Foo foo;

    public EasyFooImpl(Foo foo) {
        this.foo = foo;
    }

    @Override
    public String foo() {
        try {
            return foo.foo();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}


The latter delegates to the former, wrapping all exceptions in runtime exceptions.

And finally a factory:

public class FooFactory {
    public static Foo createFoo() {
        return new FooImpl();
    }

    public static EasyFoo createEasyFoo() {
        return new EasyFooImpl(new FooImpl());
    }
}


The benefits:

  • the user of the API can choose how he likes to use the implementation. If he doesn't intend to do anything with the checked exceptions, he can use the "easy" version



  • you support only one interface. The 2nd is the same, and you'll just have to add the methods that you have in the main one.



-
the user can use the EasyFoo in p

Solution

Just accept the fact that the exception is unchecked and move on.

The industry is moving away from checked exceptions: C++ never had them, C# decided not to follow Java in this place, and the latest frameworks for Java are using unchecked exceptions.

Face it, checked exceptions are a nice idea that doesn't work in practice.

As a result, the thing you try in your code, will never pass any code review I'll be part of.

Context

StackExchange Code Review Q#698, answer score: 4

Revisions (0)

No revisions yet.