java - 不能在 OnClickListener 上抛出 IOException

标签 java android

我正在尝试制作一个应用程序内录音机,但由于某种原因我无法抛出 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/

相关文章:

java - HttpSessionListener - GC 注意事项?

java - 让驱动程序等待条件为真并在条件为假时继续的最佳方法是什么?

java - 谷歌游戏控制台 : 'Your app signing key' s encryption strength does not meet Google Play's recommended minimum standard'

java - BaseAdapter.notifyDataSetChanged 不更新其 ListView

Android Navigation,我可以移动任何未连接的 fragment

java - 两个 lucene 索引需要两个 Directory 对象?

java - <html> 和 <html :html> element in JSP? 之间有什么区别

java - Spring:@PropertySource 的编程等价物是什么

Android SupportMapFragment 没有创建 View 报错

Android: View 持有者上的 classCastException