Home > Enterprise >  Java: Is There Any Way to Specify When an Exception Will be Thrown?
Java: Is There Any Way to Specify When an Exception Will be Thrown?

Time:10-02

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:

  1. Add a try catch block around every doSomething call
  2. Add a throws statement in main
  3. Get rid of the throws statement in doSomething
  4. 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?

CodePudding user response:

It really depends on the context You are working with.

If You want the code to stop executing at the moment the Exception is thrown, You could use Runtime exceptions, You don't have to catch them.

The good use case would be a REST endpoint. If something goes wrong during the computation of the response, we could throw ResponseStatusException - the Runtime exception which would immedeately return the Http Response Error to the client and stop any further execution of the code.

In contrary, if You have a logic which has to be executed even if the exception was thrown, the best way would be to use try - catch blocks, or to add throws statement to the method declaration and try - catch in parent method.

  • Related