This week's giveaway is in the Spring forum.
We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!
See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception doubt

 
Srinivas Kumar
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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");
}
}
1.Compiler error complaining about the catch block where no IOException object can ever be thrown.
2.Compiler error - IOException not found. It must be imported in the first line of the code.
3.No compiler error. The lines "Before Try" and "At the end" are printed on the screen.

Answer is given as 1.
If the body of try block does not contain any code, can't we catch any exception?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How would you cause an exception to be thrown if there isn't any code?
 
Srinivas Kumar
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I replace IOexception with Throwable, the code does not give any compilation error.howz that possible?

Here is the code.

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");
}
}
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because all unchecked exceptions are subclasses of Throwable.
 
Antonio Trapero
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you dont throw any exception inside try/catch body , nor a call to a method that throws the exception, you have a compilation error. If you catch Throwable or error, it let you compile, cause errors could happen any time in runtime (you dont declare it).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic