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

Exception problem

 
nitude gupta
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

while practising on eof the mock from http://www.valoxo.ch/jr/mocks/mock01a.html


import java.io.*;
public class Fundamental15 {
public static void main(String[] args) {
Fundamental15Sub myref = new Fundamental15Sub();
try{
myref.test();
}catch(IOException ioe){}
}
void test() throws IOException{
System.out.println("In Fundamental15");
throw new IOException();
}
}
class Fundamental15Sub extends Fundamental15 {
void test() {
System.out.println("In Fundamental15Sub");
}
}


answer to this is Compiler error!!!

which says

: exception java.io.IOException is never thrown in body of corresponding try statement


Please explain?? why its a compiler error ops:

I think its basic concept regarding exception but unable to figure it!!!

 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Checked exceptions except Exception need to be thrown before catching.
 
Ankit Garg
Sheriff
Posts: 9528
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you write

myref.test();

Type of myred is Fundamental15Sub. So the compiler will look at test method of Fundamental15Sub class which looks like this

void test()

So the compiler knows that it doesn't throw any checked exception. So when you enclose the call into a try catch block and catch IOException which is a checked exception, the compiler will see that the IOException is not thrown by the code in the try block. So it will give a compilation error. As punit said, this is true for all checked exceptions exception Exception and Throwable as they have unchecked sub classes RuntimeException etc...
 
nitude gupta
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you

Both of you Punit and Ankit

your reply was of great help!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic