user3369592
user3369592

Reputation: 1447

handle exceptions in stream java 8

I have a string:

"1, 2, 3 , -4"

it is split by ", ". I have a function to convert a number to a enum type which works fine. I want to use java 8 to convert this string to a list of enum objects.

Pattern pattern = Pattern.compile(", ");
List<f> fList = pattern.splitAsStream(str)
  .map(s -> {
    try {
      return this.getEnumObject(Integer.valueOf(s), f.class);
    }
    catch (NoEleException e) {
      e.printStackTrace();
    }
  })
  .collect(Collectors.toList());

This gives me an error:

missing return type.

How could I fix it?

Upvotes: 5

Views: 7350

Answers (4)

user514949
user514949

Reputation: 79

If you are certain that this won't happen you could return null in the catch and filter for non null before collecting:

Pattern pattern = Pattern.compile(", ");
List<f> fList = pattern.splitAsStream(str)
  .map(s -> {
    try {
      return this.getEnumObject(Integer.valueOf(s), f.class);
    }
    catch (Exception e) {
      return null;
    }
  })
  .filter(Objects::nonNull)
  .collect(Collectors.toList());

Upvotes: 0

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36401

Basically to ways of managing this:

  1. catching the exception and return some value or encapsulate values in Optionals and filter accordingly
  2. Throwing a RuntimeException which chains the original one

In the first case we use Optional to put something into the stream on error, and then manage these empty values further in the stream:

pattern.splitAsStream(str)
.map(s -> {
  try {
    return Optional.of(this.getEnumObject(Integer.valueOf(s), f.class));
  }
  catch (NoEleException e) {
    e.printStackTrace();
    return Optional.empty();
  }
 })
.filter(Optional::isPresent) // remove empty optionals
.map(Optional::get) // unwrap them
.collect(Collectors.toList());

In the second case the stream is stopped and you can then try to catch the RuntimeException and unchain the original one:

pattern.splitAsStream(str)
.map(s -> {
  try {
    return Optional.of(this.getEnumObject(Integer.valueOf(s), f.class));
  }
  catch (NoEleException e) {
    e.printStackTrace();
    throw new RuntimeException(e); // stop the stream
  }
 })
.collect(Collectors.toList());

Upvotes: 5

Julian Rubin
Julian Rubin

Reputation: 1235

You can create Null Object like MissingElement, return it in catch and them filter it out after map.

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56423

Currently, if an exception occurs no result will be returned hence the compilation error. You'll need to return a value after the catch block .

Upvotes: 6

Related Questions