,如果我有一個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
}
}
可以拋出異常 –
如果這是你在做真正感興趣的東西,認爲你聲明的返回類型可能不是最合適的一個。您可能還想看看[空對象模式](https://en.wikipedia.org/wiki/Null_Object_pattern)。 – JonK
是的,如果你真的有特殊情況,只能使用例外。否則,您應該測試方法以外的情況。 – abbath