aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Broader exceptions thrown by methods that implement interfaces Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Broader exceptions thrown by methods that implement interfaces" Watch "Broader exceptions thrown by methods that implement interfaces" New topic
Author

Broader exceptions thrown by methods that implement interfaces

Sandra Bachan
Ranch Hand

Joined: Feb 18, 2010
Posts: 434
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...






Marriage Made in Heaven
http://www.youtube.com/user/RohitWaliaWedsSonia
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9305
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

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!


|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Oh, Ankit answered!
Sandra Bachan
Ranch Hand

Joined: Feb 18, 2010
Posts: 434
Thank you
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Broader exceptions thrown by methods that implement interfaces