Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Doubt

 
Murali Veeraiyan
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Q,

public class tester
{
public static void test()
{
System.out.println("test");
}

public static void main(String[] args)
{
try{
test();
}catch(Exception e)
{}
}
}
***********************************************
The abv compiles...while the one below doesnt...why?
***********************************************

import java.io.*;

public class tester
{
public static void test()
{
System.out.println("test");
}

public static void main(String[] args)
{
try{
test();
}catch(IOException e)
{}
}
}

I think IOException is a direct subclass of Exception...and is not a subclass of RuntimeException
Why this difference in behaviour in the abv two programs...where i hav only changed the exception type...
I may hav not understood some important concept...plz explain
 
Manuel Moons
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer is very simple. The compiler knows that an IOException can never occur because nowhere in the calling code an IOException is thrown. An IOException is a checked exception so it cannot be thrown if not declared.
All checked exceptions and runtime exceptions extend from exception. A runtime exception does not have to be placed in the throws clause of a method (constructor, ...). A runtime exception can thus be thrown at any given time by any given code. The compiler will not block the catch(Exception) clause because it is always acceptable(since it is the superclass of all exceptions). You will however never be able to catch an IOException (or other checked exceptions) there because it is never thrown.
 
Murali Veeraiyan
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx Moons for the reply.It really helped.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic