Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Broader exceptions thrown by methods that implement interfaces

 
Sandra Bachan
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question from Enthuware

Consider these two interfaces:

interface I1
{
void m1() throws IOException;
}
interface I2
{
void m1() throws SQLException;
}

What methods have to be implemented by a class that says it implements I1 and I2 ?


I selected

public void m1() throws Exception

which is wrong

Is this because m1() is throwing a broader Exception?

Then please explain why the class that implements interface I1 and I2 can throw Exception. Please see Enthuware's explanation below:

When interfaces are involved, more than one method declaration may be implemented by a single method declaration. In this case, the overriding declaration must have a throws clause that is compatible with ALL the overridden declarations. The declaration public void m1(){} satisfies both the declarations. Example...





 
Ankit Garg
Sheriff
Posts: 9510
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then please explain why the class that implements interface I1 and I2 can throw Exception.

A class never throws an exception, methods do. In the code the overriding m1 method is actually not throwing any exception. Thats the point. The reason for throwing Exception from the main method is completely different and has nothing to do with TestClass implementing I1 and I2...
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sandra Bachan wrote:
Is this because m1() is throwing a broader Exception?

Yes, and you are mixing two different things here. Declaring the main() method as it throws Exception and overriding the method m1() are two different things!
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, Ankit answered!
 
Sandra Bachan
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic