My understanding about exceptions was, When an exception is thrown from try block, its an object of some type which will then fit into catch block's reference variable, but I am not sure whether the compiler checks the type of the object i.e thrown or the references? Till now I learnt that objects are created at the run time so, there is no way that compiler knows about them, but still when reference is parent, and object is child it knows the relation, and it allows the casting accordingly! Similarly Exceptions,
My this code is fine
But, this code wont compile
I may sound silly, but really stuck or confused to know, whether the object type that we should declare in throws clause or the reference type?
Prathima gaitonde wrote:I may sound silly, but really stuck or confused to know, whether the object type that we should declare in throws clause or the reference type?
I think I know why you get confused about both examples.
Let's start with a small java history lesson When you compile the 1st code snippet with Java 6, you'll get a compiler error because you rethrow an exception of type Exception but the throws clause lists a subclass. So you would have to change the code like this in order to successfully compile this code.Another workaround would be of course to change the type of parameter e in the catch-clause to IOException. This is how exception handling and rethrowing works in Java 6 (and before).
But with Java 7 the mechanism of rethrowing exception has changed: The Java SE 7 compiler performs more precise analysis of rethrown exceptions than earlier releases of Java SE. This enables you to specify more specific exception types in the throws clause of a method declaration. More info can be found here. So that means, although you catch an exception of type Exception, the compiler knows it can only be of type IOException and thus allows you to have a throws-clause listing just the IOException. And this works with multiple checked exceptions as well, illustrated in this code snippet:So because the compiler does a better analysis of the code, you don't need a catch-clause with Exception (like in Java 6 and before), but you can list the concrete exception classes in the throws-clause of your method.
Now in your second example, you don't use a try/catch clause at all. You are just throwing an exception using a reference variable. So the compiler knows the type of the reference variable (Exception) you'll throw and knows the type of the method's throws clause (IOException, a subclass of Exception). He doesn't know (nor care) about the actual object the reference variable refers to.
It's similar to when you pass an Animal reference variable to a method which expects a Cat parameter. You'll get a compiler error as Animal IS-NOT-A Cat. A code snippet to illustrate: