• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Do not understand answer

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, I am studying for SJCP 1.5. I have a study book and do not understand a question/answer. Can someone please help me. Here is the question:

Given:
import java.io.*;
class Master {
String doFileStuff() throws FileNotFoundException {
return "a";
}
}

class Slave extends Master {
public static void main(String[] args) {
String s = null;
try {
s = new Slave().doFileStuff();
}
catch (Exception x) {
s = "b";
}
System.out.println(s);
}
// Insert code here
}

Does the following compile correctly and produce the output "b" when inserted at // Insert code here

String doFileStuff() throws NumberFormatException, FileNotFoundException {
return "b";
}

The answer says it works but I answered it did not since NumberFormatException is not thrown by Master so it is not a valid override.

Can someone help me understand?

thanks
Harry
 
Harry Brearley
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
still do not understand. It compiles. it runs, it returns "b"
BUT NumberFormatException cannot be thrown by Master.doFileStuff()
?
 
Ranch Hand
Posts: 236
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
NumberFormatException is a runtime exception which can be declared by overridden methods.
 
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
While overiding, the overidden method cannot throw new or broader checked exceptions however it can throw any number of unchecked exceptions.
 
it's a teeny, tiny, wafer thin ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic