user3055593
user3055593

Reputation: 79

Interfaces and exceptions

I was reading about Interfaces on tutorialspoint, and came across the following:

"Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method."

Could anyone explain to me what exactly this means?

Upvotes: 0

Views: 1101

Answers (2)

resueman
resueman

Reputation: 10613

Checked exceptions are exceptions that must be declared in the type signature of a method that might throw them. What that quote is saying is that a class that implements an interface should not add any checked exceptions into the signature of the methods its implementing from the interface.

So if you have an interface like this:

interface NoExceptions{
    void safeMethod();
}

You are forbidden from declaring a class like this:

class UnsafeClass{
    @Override
    void safeMethod() throws IOException{}
}

Since it's modifying the type signature. Instead, those exceptions should be handled inside the method.

This is because the point of checked exceptions is to ensure that the calling code will handle a possible problem that could occur. Trying to add in the exception in a subclass removes that safety:

UnsafeClass uc = new UnsafeClass();
uc.safeMethod(); //Not allowed, because the exception is not handled
NoExceptions ne = uc;
ne.safeMethod(); //Becomes allowed, because the interface does not declare an exception

Because of that, you are forbidden from adding exceptions like that.

You could, however, write an implementation that throws a subclass of the checked exception declared on the interface. That will always be a safe operation, because the subclass can be used as a drop-in replacement for it's superclass.

Upvotes: 1

Nyavro
Nyavro

Reputation: 8866

This means that if method of interface I declared as throwing some checked exception E than some client code uses interface should handle this checked exception explicitly (by try-catch or throwing further). And if you try to declare some more checked exceptions (E1) in your class C implementing I this will break the logic of application: clients of I has no idea about exceptions thrown other than E.

Actually, compiler won't allow you to do it

Upvotes: 1

Related Questions