为什么我必须使用 try/catch 包围?

huangapple go评论146阅读模式
英文:

Why I have to surround with try/cacth

问题

我有一个方法

private void writeObject(ObjectOutputStream oos) throws IOException 

在方法体中,我写了一些HashMap的keySet

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

看起来没问题
但是如果我想要用以下代码替换这部分

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

我必须用try/catch将其包围。像这样

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

而且我不明白为什么

更新 我不明白为什么我需要在方法体中处理异常,如果我在方法标题中声明我想要将其抛出。

英文:

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.

答案1

得分: 1

这是因为forEach()接受Consumer作为参数。而Consumer没有声明抛出任何已检查异常。因此,你的lambda表达式也应该是Consumer,并且不应抛出任何已检查异常。因此,任何已检查异常都应该在你的lambda体内捕获。

英文:

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.

答案2

得分: 0

**try** 块将执行可能会抛出异常的敏感代码
**catch** 块将在 **try** 块中抛出一个捕获到的异常类型时使用

方法原型中的 **throws** 关键字用于指定你的方法可能会抛出指定类型的异常。当你有一个已检查异常(必须处理的异常),而你不想在当前方法中捕获它时,这很有用。
英文:

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.

huangapple
  • 本文由 发表于 2020年8月26日 17:56:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63595118.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定