I have code something like this pseudo code:
void doSomething(int data) throws Exception{
if(data < 10) throw new Exception("Exception thrown"); // throws an exception based on a condition
else { ... } // logic goes here
}
When I try to call doSomething in the main function, it give me an error:
public static void main(){
doSomething(11); // Error! unreported exception
}
Here is a link to the previous example.
So I have to do one of the following:
- Add a try catch block around every doSomething call
- Add a throws statement in main
- Get rid of the throws statement in doSomething
- Make the condition a precondition, so that not following it results in undefined behavior or something similar.
3 will not work, because doSomething may throw an exception when a client is using it. 1 and 2 are simply redundant, and I think they should be avoided.
Finally, 4 is the most appealing to me (being primarily a C++ coder) but runs contrary to Java programming.
My question is: What is the best way out of the mentioned options (or any other options), and what is the best way to implement it?