| Author |
Exception test
|
santhoshkumar samala
Ranch Hand
Joined: Nov 12, 2003
Posts: 156
|
|
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
|
santhosh<br />SCJP,SCWCD
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
|
In the code you listed, system should have been System. When I changed that, it compiled without an error.
|
 |
pravin kumar
Ranch Hand
Joined: Nov 03, 2005
Posts: 30
|
|
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
Joined: Feb 07, 2005
Posts: 2341
|
|
|
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
Joined: Nov 03, 2005
Posts: 30
|
|
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
Joined: Feb 07, 2005
Posts: 2341
|
|
|
The catch block can handle an exception of type IOException since IOException is a subclass of Exception.
|
 |
 |
|
|
subject: Exception test
|
|
|