Page 1 of 1

About Question enthuware.ocpjp.v7.2.1204 :

Posted: Sun Apr 28, 2013 8:09 am
by RobynBackhouse
Hi there,
Quick question about this as I'm confused (again!)..
I have been playing around with it, and in your answer it says this:

Code: Select all

catch (FileNotFoundException | IndexOutOfBoundsException e) {             
    e = new IOException();
}
The exception parameter in a multi-catch clause is implicitly final. Thus, it cannot be reassigned. Had there been only one exception in the catch clause, it would have been valid.
I'm not able to reassign the value of e to a new exception even in a catch clause with a single exception, unless it is to a new exception of the same type.
e.g. This works fine, assigning e to a new FileNotFoundException:

Code: Select all

try { throw new FileNotFoundException("hello"); }
catch (FileNotFoundException e){
    e = new FileNotFoundException("goodbye");
    e.printStackTrace();
}


But this will not run, throwing an error when trying to assign it to a different type:

Code: Select all

try { throw new FileNotFoundException("hello"); }               
catch (FileNotFoundException e){
	e = new IOException("goodbye");
	e.printStackTrace();
}
Error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from IOException to FileNotFoundException


Do you have any examples of how this works when assigning e to a different type of exception please? Or explain a little more how it works?

Many thanks. :)

Re: About Question enthuware.ocpjp.v7.2.1204 :

Posted: Sun Apr 28, 2013 9:25 am
by admin
You are right. Rules of assignment cannot change. For example, you can't assign a Car to a Plant! No matter what. This is irrespective of whether it is a multi catch or single catch. The explanation is trying to make that point but using a wrong example. It should be like this:

Code: Select all

catch (IOException | IndexOutOfBoundsException e) {             
    e = new FileNotFoundException(); //This would be valid if you have catch(IOException e)
    e = new IOException(); //This would be valid if you have catch(IOException e)
    e = new Exception(); //This would be valid if you have catch(Exception e) but not catch(IOException ioe)
}
Fixed.

thank you for your feedback!

Re: About Question enthuware.ocpjp.v7.2.1204 :

Posted: Mon Apr 29, 2013 3:11 pm
by RobynBackhouse
Oh I seeeee...
Yeah that makes sense now.
Many thanks! :D