gpt4 book ai didi

java - 不能在 OnClickListener 上抛出 IOException

转载 作者:行者123 更新时间:2023-11-29 04:18:25 26 4
gpt4 key购买 nike

我正在尝试制作一个应用程序内录音机,但由于某种原因我无法抛出 IOException,因为与 OnClick 方法发生冲突。

play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) throws IOException {

MediaPlayer m = new MediaPlayer();
m.setDataSource(outputFile);
m.prepare();
m.start();
Toast.makeText(getContext(), "Playing audio", Toast.LENGTH_SHORT).show();
}
});

throws IOException 部分对于您稍后可以看到的行是必需的,但它似乎会导致某种冲突。整个事情都在 onCreateView 方法中,并且它在一个 fragment 中,如果这是相关信息的话。非常感谢任何帮助!

最佳答案

方法覆盖

Rule: An overriding method (the method of child class) can throw any unchecked exceptions, regardless of whether the overridden method (method of base class) throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw those checked exceptions, which have less scope than the exception(s) declared in the overridden method.

在您的情况下,onClick()View.OnClickListener 的重写方法。由于 View.OnClickListener 中的 onClick() 不会在父类/接口(interface)中抛出任何异常,因此您无法抛出已检查的异常。

IOException 是一个检查异常。您可以尝试抛出 ArrayIndexOutOfBoundsException 它不会给出编译时错误。

除了 onClick()throws 似乎没有任何用处。 throws 用于传递调用链中的异常。由于 onClick() 是一个事件监听器,因此没有必要抛出异常。您应该使用 try/catch 并在 onClick() 本身内部处理异常。

关于java - 不能在 OnClickListener 上抛出 IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50800972/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com