1

I have multiple objects with value stored in -

object.getList().get(0).getSomeObject.getName(0)

It's possible, that list is empty so-

object.getList().get(0)

throws a NPE

I want to pass-

object.getList().get(0).getSomeObject.getName()

to another method and handle the exception there.

For example:

// calling the method
myMethod(object.getList().get(0).getSomeObject.getName());

public void myMethod(Object o){
    try {
        String name = o;
    }catch (Exception e){
        // do something
    }
}

Is it possible to do something like that -

EvaluateLaterObject elo = new EvaluateLaterObject(object.getList().get(0).getSomeObject.getName());
myMethod(elo);

public void myMethod(EvaluateLaterObject elo){
    try {
        String name = elo.getValue();
    }catch (Exception e){
        // do something
    }
}

Thank you in advance!

vikash singh
  • 1,479
  • 1
  • 19
  • 29
PaBo
  • 13
  • 3
  • Probably duplicate of this https://stackoverflow.com/questions/18198176/java-8-lambda-function-that-throws-exception – SME_Dev Sep 25 '19 at 12:06

2 Answers2

2

You can use a functional interface such as Supplier and a lambda

myMethod(() -> object.getList().get(0).getSomeObject.getName());

public void myMethod(Supplier<String>){
    try {
        String name = elo.get();
    }catch (Exception e){
        // do something
    }
}

If you want to support any exception, you'll need to define your own functional interface e.g.

@FunctionalInterface
interface ThrowableSupplier<T>
{
    T get() throws Throwable;
}
Michael
  • 41,989
  • 11
  • 82
  • 128
1

Either what already was given by Michael

Supplier<String> objectSupplier = () -> object.getList().get(0).getSomeObject.getName();

public void myMethod(Supplier<String> objectSupplier){
    try {
        String name = objectSupplier.get();
    }catch (Exception e){
        // do something
    }
}

Which does not really handle the exception.

Or use the optionality. Assuming the list items have class ListItem and getSomeObject is of class Item:

Optional<String> nameOpt = object.getList().stream()  // Stream<ListItem>
        .findFirst()                                  // Optional<ListItem>
        .map(ListItem::getSomeObject)                 // Optional<Item>
        .map(Item::getName);                          // Optional<String>

public void myMethod(Optional<String> nameOpt){
    nameOpt.ifPresent(name -> System.out.println(name));
    String nm = nameOpt.orElse("(No Name)");
}
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138