• 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

Exception

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I know that Exception is a checked exception.

My question is when I try this code:

import java.io.*;

public class AQuestion2{
public static void main(String args[]){
System.out.println("Before Try");
try{}
catch(IOException e){
System.out.println("Inside Catch");
}
System.out.println("At the End");
} // end of main
}//end of class

It doesn't compile.

But say we change the catch argument to "Exception", it compiles fine and produces an output.
Isn't that "Exception" is also a checked exception and should not also compile?

What is something that I am missing here?

Thanks!
 
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

When you specify that the catch is IOException...it is a checked excpetion...but in your try block there is no code that throws such an ioexception...and so catch block is unreachable code..

Hence the compiler error..

But when you write Exception in the catch block...it can mean either for checked or runtime exception(unchecked)...hence the compiler doesnt enforce the same rule ....

Correct me if am wrong..

 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
very good reply!
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
since you are catching IOException which is never thrown in corrosponding try block compiler will give error saying "IOException never thrown in corrosponding try block". For this code to compile you have to either throw IOException or use any method which throws IOException like,

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.read();

Then it will compile
 
reply
    Bookmark Topic Watch Topic
  • New Topic