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
Joined: Sep 22, 2000
Posts: 53
posted
0
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
Joined: Aug 30, 2000
Posts: 3141
posted
0
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