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 test

 
santhoshkumar samala
Ranch Hand
Posts: 156
Eclipse IDE Hibernate Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.io.IOException;
public class ExceptionTest{
public static void main (String[]args)
{
try {
methodA();
}
catch (Exception e) //compilation error here
{
system.out.println("Caught Exception");
}
}

public static void methodA () throws IOException{
throw new IOException ();
}
}


why the above code gives compilation error at catch(Exception) line?

I thought that we can put catch(Exception e) for any exception

message is:Type mismatch cannot convert from Exception to Throwable
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the code you listed, system should have been System. When I changed that, it compiled without an error.
 
pravin kumar
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey i heard either you could declare or catch the exception
so it should not compile as
method() method throw exception and also catch the same in try-catch block
please explain
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't understand your question. There is a rule that if a method can cause a checked exception to occur, then we must either declare that exception in the throws clause of the method if possible, or must deal with the exception with a try-catch block. IOException is a subclass of Exception, so if method() does throw an IOException, it can be caught by the catch block that can handle an Exception.
 
pravin kumar
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.io.IOException;
public class ExceptionTest{
public static void main (String[]args)
{
try {
methodA();
}
catch (Exception e) //compilation error here
{
system.out.println("Caught Exception");
}
}

public static void methodA ()throws IOException{
throw new IOException ();
}
}

here we throw IOException in the methodA..
so according to my understanding ..as u throw IOException in the method i.e. u declared the exception throwed in the method ..the same should not catched in try-catch block.
[b] please explain the same
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The catch block can handle an exception of type IOException since IOException is a subclass of Exception.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic