2015-10-19 39 views
0

,如果我有一个void方法,从它终止在一定条件下的方法之一是使用关键字“返回”,这样的事情如何从返回一个字符串的方法终止

public void test() { 
    if (condition()) { 
     return; 
    } 
    } 

什么如果我有一个返回字符串的方法

public String test() { 
if (condition()) { 
    //what to do here to terminate from the method, and i do not want to use the null or "" return 
} 
} 
+0

可以抛出异常 –

+1

如果这是你在做真正感兴趣的东西,认为你声明的返回类型可能不是最合适的一个。您可能还想看看[空对象模式](https://en.wikipedia.org/wiki/Null_Object_pattern)。 – JonK

+0

是的,如果你真的有特殊情况,只能使用例外。否则,您应该测试方法以外的情况。 – abbath

回答

5

终止方法的执行而不返回值的唯一方法是抛出异常。

public String test() throws SomeException { 
    if (condition()) { 
    throw new SomeException(); 
    } 
    return someValue; 
} 
0

您可以通过抛出异常停止方法执行,但更好的方法会像你回来,如果你不希望返回“像一些价值”,比你可以使用类似“noResult”或“NOVALUE”和你可以与它打电话给它检查

public static void main(String[] args) { 
    try { 
     test(); 
    } catch(Exception e) { 
     System.out.println("method has not returned anything"); 
    } 
} 

public static String test() throws Exception { 
    try { 
     if (true) { 
      throw new Exception(); 
     } 
    } catch(Exception e) { 
     throw e; 
    } 
    return ""; 
} 
1

随着番石榴可选或Java 8可选,你可以做到这一点。

public Optional<String> test() { 
    if (condition()) { 
     return Optional.absent(); 
    } 

    ... 
    return Optional.of("xy"); 
} 
相关问题