It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Checked Exception Confusion 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 "Checked Exception Confusion" Watch "Checked Exception Confusion" New topic

Checked Exception Confusion

Maneessh saxena
Ranch Hand

Joined: Oct 03, 2006
Posts: 125
Hi Ranchere
I am new to javaranch . I have a confusion related to checked Exception . As in code showm below if we have empty try block and catches ’IOException’ ( as at line 1 ) it will give a compile time error saying
::“exception is never thrown in body of corresponding try statement”
Where as if we catch ‘Exception’ with an empty try block code compiles fine.
I just want to know both ‘IOException’ & ‘Exception’ are checked exceptions than why code with line 2 compiles fine whereas code with line 1 fails to compiles ………

code ::

class ZZ{
public static void main(String args[]){

try{ }catch(IOException e){e.printStackTrace();}//line 1
//try{ }catch(Exception e){e.printStackTrace();}//line 2

Thanks in advance

SCJP 1.4, SCWCD 1.5
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
It's because even though Exception itself is a checked Exception, it has subclasses which are unchecked (RuntimeException and its subclasses).

IOException and its subclasses are checked exceptions.
Dinuka Arsakularatne
Ranch Hand

Joined: Aug 12, 2006
Posts: 198
IOExceptions are thrown only if you use io methods such as FileWriter, PrintWriter, BufferedWriter etc. becos there is no code in you try block with that kind of code providing a catch block for it will give a compile error because the compiler can say for sure that IOException will never be thrown becos you are not using any io methods. but when you say just Exception then anytype of exception will be caught because you are not specifying a specific exception. hence anything that can be considered throwable will be caught by just using Exception. hence the empty tags will be ok to use with the Exception.

hope this helps

if who i am is what i have, and what i have is lost, then who am i?<br /> <br />SCJP 5.0<br />SCWCD 1.4<br />SCBCD preparing
I agree. Here's the link:
subject: Checked Exception Confusion
It's not a secret anymore!