p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   BOOK: Professional C++ (http://p2p.wrox.com/forumdisplay.php?f=158)
-   -   java does not require exception be caught or declared (http://p2p.wrox.com/showthread.php?t=93896)

murray hughes December 4th, 2014 07:26 PM

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.


All times are GMT -4. The time now is 10:43 PM.

Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.