0

I have method

private void writeObject(ObjectOutputStream oos) throws IOException 

In body I write keySet of some HashMap

        for(E e : map.keySet()) {
        oos.writeObject(e);
    }

And it's look OK But if I want to replase this code on

map.forEach((k, v) -> oos.writeObject(k));

I have to surround it with try/catch. Like this

        map.forEach((k, v) -> {
        try {
            oos.writeObject(k);
        } catch (IOException e) {
            e.printStackTrace();
        }
    });

And I can't understand for what

Update I can't understand why I need to processed exception in method body if I anounce in method title that I want it to throw away.

boomzin
  • 1
  • 2

2 Answers2

1

That is because forEach() takes Consumer as argument. And Consumer isn't declared throws any checked exception. So your lambda should also be Consumer and do not throw any checked exceptions. So any checked exception should be caught in you lambda body.

Kirill
  • 49
  • 8
0

The try block will execute a sensitive code which can throw exceptions The catch block will be used whenever an exception (of the type caught) is thrown in the try block

The throws keyword in the method prototype is used to specify that your method might throw exceptions of the specified type. It's useful when you have checked exception (exception that you have to handle) that you don't want to catch in your current method.

danoblinux
  • 56
  • 7