user4458270
user4458270

Reputation:

How to stop execution of a called method in java and continue execution of calling method

Consider the following code snipett:

public String testMethod1(int i, int j)
{
//do something
testmethod2(i,j);
return "some string";
}

public String testMethod2(int i, int j)
{
//do something
if(some condition)
{
//Stop execution of this method
//continue execution of previous method as if this method was never called
}
return "some string";
}

Is there a way that we can achieve something like above in java. I want the second method to stop its execution and the first method should continue as if the second method was never called

Upvotes: 0

Views: 2231

Answers (1)

Sweeper
Sweeper

Reputation: 271830

In your testMethod2, you should return to stop its execution. However, just a plain return is not enough as your method returns a String. You must return a String or null.

My suggestion is to return an empty string (""). Why not return null? Because the calling method may want to do something with the string returned. If it is null, a NullPointerException will be thrown, which is not good!

So you should do this:

if (some condition) {
    return "";
}

Upvotes: 2

Related Questions