2015-10-19 93 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"); 
} 
相關問題