Kingo Mostafa
Kingo Mostafa

Reputation: 347

How to terminate from a method that returns a string

If i have a void method, one of the ways to terminate from it under certain condition is using the keyword "return", something like this

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

What if i have a method that returns string

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

Upvotes: 0

Views: 92

Answers (3)

heaphach
heaphach

Reputation: 1492

With Guava Optional or Java 8 Optional you can do this.

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

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

Upvotes: 1

Keval
Keval

Reputation: 1859

You can stop method execution by throwing exception ,but better approach will be like you return some value like if you dont want to return "" , than you can use something like "noResult" or "noValue" and you can check with it in caller

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

Upvotes: 0

Eran
Eran

Reputation: 393811

The only way to terminate a method's execution without returning a value is by throwing an exception.

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

Upvotes: 5

Related Questions