Pretty silly question. Based on the code:
public static int sum(String a, String b) { int x = Integer.parseInt(a);
Could you say whether this is good Java or not? I am saying that NumberFormatException is an exception. You do not have to specify it as part of the sum() signature. Moreover, as I understand it, the idea of unchecked exceptions is to signal that the implementation of the program is incorrect, and even more, catching unchecked exceptions is a bad idea, since it is like fixing a bad program at runtime.
Someone please clarify if:
- I have to specify a
NumberFormatException as part of the method signature. - I have to define my own checked exception (
BadDataException ), handle a NumberFormatException inside the method and throw it as BadDataException . - I have to define my own test exception (
BadDataException ), check both lines in some way, like regular expressions, and throw my BadDataException if they do not match. - Your idea
Update
Imagine that this is not an open source infrastructure that you should use for some reason. You look at the signature of the method and think - "OK, it never throws." Then, someday, you get an exception. This is normal?
Update 2 :
There are a few comments saying that my sum(String, String) bad design. I absolutely agree, but for those who believe that the original problem simply will not appear if we have a good design, here's another question:
The problem definition looks like this: you have a data source where numbers are stored as String s. This source can be an XML file, a web page, a desktop window with 2 edit fields, whatever.
Your goal is to implement logic that takes these 2 String s, converts them to int and displays a message box that says: "sum xxx".
No matter which approach you use to develop / implement this, you will have these two points of internal functionality:
- The place where you convert
String to int - The place where you add 2
int s
The main question of my original post:
Integer.parseInt() expects the correct string to be passed. Whenever you pass a bad string, it means that your program is incorrect (and not "your user idiot"). You need to implement a code fragment in which, on the one hand, you have Integer.parseInt () with MUST semantics, and on the other hand, you need to be in order with cases when the input is incorrect - SHOULD use semantics.
So, briefly: how can I implement SHOULD semantics if I only have MUST libraries.