Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in Exception.

 
Sunitha Sounderrajan
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone please explain why the Example 1 posted below compiles and runs and the the Example 2 does not compile?
Example :1
public class AQuestion
{
public static void main(String args[])
{
System.out.println("Before Try");
try
{
}
catch(Throwable t)
{
System.out.println("Inside Catch");
}
System.out.println("At the End");
}
}
This compiles and prints "Before Try" and "At the End".
Example : 2
public class AQuestion
{
public static void main(String args[])
{
System.out.println("Before Try");
try
{
}
catch(java.io.IOException t)
{
System.out.println("Inside Catch");
}
System.out.println("At the End");
}
}
gives a compiler error.
Compiler error complaining about the catch block where no IOException object can ever be thrown.
Thanks,
Sunitha. S
 
Harry Singh
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would think this is because any program can throw a runtime exception. So java allows the Thowable to be thrown since it is a superclass of RuntimeException. It also allows java.lang.Exception ( you can try that. It works ) But anything below that ( except for RuntimeException ) can not be thrown.
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sunitha,
Believe Harry is right about the Throwable; any code can throw a runtime exception. Think the error is because you have an empty <code>try</code> block. You're not actually trying to do any I/O so there is no way an I/O exception can be thrown.
Hope that helps
Jane
 
Sunitha Sounderrajan
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Harry and Jane,
Yes. it did help.
Thanks, I appreciate it.
Sunitha. S
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic