简体   繁体   English

结束调用此方法的方法

[英]end the method that call this method

Is there a way to end the method that calls on the method that the code is in. Let me explain if you have some code like this. 有没有一种方法可以结束调用代码所在方法的方法。让我解释一下您是否有这样的代码。

int value;
value = method();
value = 3;

If I got it work like I want then the execution of the code would end on line 2 and line 3 would never be executed. 如果我按我的意愿工作,那么代码的执行将在第2行结束,而第3行将永远不会执行。 basically it would be like there was a return between line 2 and 3. Is is something like this possible with Java? 基本上,这就像第2行和第3行之间有回报。对于Java来说,这样可能吗?

Edit: Ok i think a lot of people have misunderstood me. 编辑:好的,我认为很多人误会了我。 The code that end the code on in this method on line 2 should be inside of method() and it should not be possible to avoid this outside this method if it's call inside of a try for example. 在第2行的此方法中以该代码结尾的代码应位于method()内部,并且例如,如果在try内部调用,则应该无法避免在此方法之外。

Your example is a bit abstract, a real one might result in better answers. 您的示例有点抽象,一个真实的示例可能会带来更好的答案。 In general though there are two ways this is normally achieved: 通常,通常有两种方法可以实现此目的:

  1. Return a special value eg -1 返回一个特殊值,例如-1

     int method() { if (/* something is wrong */) { return -1; } // Process as normal and return real value } ... int value; value = method(); if (value == -1) { value = 3; } 
  2. Throw an exception in method() 在method()中引发异常

     int method() throws IllegalStateException { if (/* something is wrong */) { throw new IllegalStateException(); } // Process as normal and return real value } ... int value; try { value = method(); } catch (IllegalStateException e) { value = 3; } 

You can terminate the current program / JVM with System.exit 您可以使用System.exit终止当前程序/ JVM

java.lang.System.exit(0 /* Status */ );

If you don't want to exit then you have to use return. 如果您不想退出,则必须使用return。

in a void method do 用无效方法

int value;
value = method();
return;

Or if method has the same return signature as the current method 或者方法的返回签名与当前方法相同

int value;
return value = method();

如果条件值=您期望的收益,则添加;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM