如何从返回字符串的方法终止

时间:2015-10-19 07:53:00

标签: java

如果我有一个void方法,在某些条件下终止它的一种方法是使用关键字" return",类似这样的

    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
 }
}

3 个答案:

答案 0 :(得分:5)

在不返回值的情况下终止方法执行的唯一方法是抛出异常。

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

答案 1 :(得分:1)

使用Guava Optional或Java 8 Optional,您可以执行此操作。

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

  ...
  return Optional.of("xy");
}

答案 2 :(得分:0)

你可以通过抛出异常来停止方法执行,但更好的方法就像你返回一些值,就像你不想返回&#34;&#34; ,你可以使用类似&#34; noResult&#34;或&#34; noValue&#34;你可以在调用者中查看它

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 "";
}