This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding and Exceptions

 
Nils Widmer
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given Following Code, why is it not allowed for MyMethod() to declare IOException in MyExp2 class( question 9 from http://www.javacaps.com/scjp_mockexams1.html )???
Overriding a method that doesnt throw Exception wont have overriden method which does throw Exception?
Do Overriden methods have some scope rule for throwing exceptions as in they can only throw exceptions that are already thrown in the overridden method of subclass??


<CODE>
import java.io.*;
class MyExp {
void MyMethod() throws IOException, EOFException {
//............//
}
}
class MyExp1 extends MyExp {
void MyMethod() {
//..........//
}
}
public class MyExp2 extends MyExp1 {
void MyMethod() throws IOException {
//.........//
}
}
</CODE>

Can an overloaded method throw an exception?
like:
<CODE>
class Shit
{
protected void m_DoShit()
{}
protected void m_DoShit(int i)
throws MyException
{}/*assume MyException is derived from IOException*/
}
class BullShit extends Shit
{
public void m_DoShit(int i)
throws IOException
{}
}
</CODE>

------------------
 
ashok khetan
Ranch Hand
Posts: 153
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nils,
for the first part of ur query, i think this is the solution:
As class MyExp2 extends class MyExp1, and also overrides the MyMethod() method of MyExp1( which is its immediate superclass). As the MyMethod() of superclass(MyExp) doesn't throw any Exception so the overriding method in its subclass can't throw any other(Except RunTimeException) exception. In short MyMethod() of MyExp2 should be defined in the context of its immediate superclass i.e. MyExp1.
hope it should be o.kay.
ashok.
 
Nils Widmer
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yups, thanks Ashok, that is clear now
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic