Quite a stupid question. Given the code:
public static int sum(String a, String b) /* throws? WHAT? */ { int x = Integer.parseInt(a); // throws NumberFormatException int y = Integer.parseInt(b); // throws NumberFormatException return x + y; }
Could you tell if it's good Java or not? What I'm talking about is, NumberFormatException
is an unchecked exception. You don't have to specify it as part of sum()
signature. Moreover, as far as I understand, the idea of unchecked exceptions is just to signal that program's implementation is incorrect, and even more, catching unchecked exceptions is a bad idea, since it's like fixing bad program at runtime.
Would somebody please clarify whether:
NumberFormatException
as a part of method's signature.BadDataException
), handle NumberFormatException
inside the method and re-throw it as BadDataException
.BadDataException
), validate both strings some way like regular expressions and throw my BadDataException
if it doesn't match.Update:
Imagine, it's not an open-source framework, that you should use for some reason. You look at method's signature and think - "OK, it never throws". Then, some day, you got an exception. Is it normal?
Update 2:
There are some comments saying my sum(String, String)
is a bad design. I do absolutely agree, but for those who believe that original problem would just never appear if we had good design, here's an extra question:
The problem definition is like this: you have a data source where numbers are stored as String
s. This source may be XML file, web page, desktop window with 2 edit boxes, whatever.
Your goal is to implement the logic that takes these 2 String
s, converts them to int
s and displays message box saying "the sum is xxx".
No matter what's the approach you use to design/implement this, you'll have these 2 points of inner functionality:
String
to int
int
sThe primary question of my original post is:
Integer.parseInt()
expects correct string to be passed. Whenever you pass a bad string, it means that your program is incorrect (not "your user is an idiot"). You need to implement the piece of code where on one hand you have Integer.parseInt() with MUST semantics and on the other hand you need to be OK with the cases when input is incorrect - SHOULD semantics.
So, briefly: how do I implement SHOULD semantics if I only have MUST libraries.
In my opinion it would be preferable to handle exception logic as far up as possible. Hence I would prefer the signature
public static int sum(int a, int b);
With your method signature I would not change anything. Either you are
Hence, exception handling in this case becomes a documentation issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With