java does not require exception be caught or declared
In the 2nd edition: some comments about java appear to be incorrect:
e.g.
"This behavior is different from that in other languages, such as Java, which requires a function or method to catch exceptions or declare them in their own function or method throw lists."
That's misleading because the third option, commonly employed in java is to use unchecked exceptions. Unchecked exceptions in java behave the same as C++ exceptions.
Here is an example demonstrating that catching/declaring exceptions is optional:
public class testException {
static Integer myValueOf(String s) throws NumberFormatException {
return Integer.valueOf(s);
}
public static void main(String[] args) {
try {
myValueOf("bad int1");
} catch (NumberFormatException e) {
System.out.println("int1");
}
myValueOf("bad int2");
}
}
Output:
int1
Exception in thread "main" java.lang.NumberFormatException: For input string: "bad int2"
at java.lang.NumberFormatException.forInputString(Unk nown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
at testException.myValueOf(testException.java:3)
at testException.main(testException.java:11)
The compiler does not require the exception thrown by method call myValueOf("bad int2"); to be caught, nor declare it in the function throw list.
To contrast two languages based on a feature that behaves the same way makes no sense.
Last edited by murray hughes; December 4th, 2014 at 07:28 PM..
Reason: fixed mistake in title
|