简体   繁体   中英

Can't throw IOException on OnClickListener

I'm trying to make an in-app audio recorder, but I am for some reason unable to throw IOException because of a clash with the OnClick method.

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();
        }
    });

The throws IOException part is necessary for lines that you can see later, but it seems to cause some sort of conflict. This whole thing is within the onCreateView method and it is within a fragment, if that is relevant information. Any help greatly appreciated!

Method overriding

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.

In your case onClick() is an overrided method from View.OnClickListener . Since onClick() in View.OnClickListener does not throw any exception in parent class/interface so you can not throw a checked Exception .

IOException is an Checked Exception. You can try to throw ArrayIndexOutOfBoundsException it will not give give compile time error .

Apart from that throws from onClick() does not seem any use . throws used to pass the Exception in calling chain. Since onClick() is a event listener there is no use of throwing the Exception. You should use try/catch and handle Exception inside onClick() itself .

According to the API, the View.OnClickListener interface defines a method onClick(View view) that doesn't throw any checked exception.

Therefore, you CANNOT throw an exception. Period. The best option is to catch this exception and do something with it. Maybe mark the case with a flag, or even store the exception.

Alternatively, though not recommended, you could throw an unchecked exception. My guess is, though, the API won't be happy about it. Better go with the first option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM