[英]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. 有没有一种方法可以在Java中实现以上类似的功能。 I want the second method to stop its execution and the first method should continue as if the second method was never called
我希望第二个方法停止执行,第一个方法应该继续执行,就好像从未调用过第二个方法一样
In your testMethod2
, you should return
to stop its execution. 在您的
testMethod2
,您应该return
以停止其执行。 However, just a plain return
is not enough as your method returns a String
. 但是,仅
return
是不够的,因为您的方法将返回String
。 You must return a String
or null. 您必须返回
String
或null。
My suggestion is to return an empty string ( ""
). 我的建议是返回一个空字符串(
""
)。 Why not return null? 为什么不返回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! 如果为null,则将抛出
NullPointerException
,这是不好的!
So you should do this: 因此,您应该这样做:
if (some condition) {
return "";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.