Daniel Sloof
Daniel Sloof

Reputation: 12706

Having generic AsyncTask handle any Exception

I have created an generic AsyncTask class, so that I can catch all Exceptions thrown when task method is executed:

public abstract class Poc<ParamType, ReturnType> 
    extends AsyncTask<ParamType, String, ReturnType> {

    abstract ReturnType task(ParamType... param);

    @Override
    protected ReturnType doInBackground(ParamType... param) {
        try {
            return task(param);
        } catch (Exception e) {
            // Make some Toast display the exception.
        }
        return null;
    }

}

I try to implement the above class by doing some thing like:

public class Use {

    public static void runIt() {
        new Poc<String, Boolean>() {
            @Override
            Boolean task(String... param) {
                return SomeObject.someMethodThatCanThrowAnException(param);
            }
        }.execute("Some String");
    }

}

However, it keeps complaining about wanting me to add try/catch statements. Even when I know that task will only be called from doInBackground which wraps it.

Can I somehow suppress this? Or what is the proper approach without having to add try/catch to every single class that subclasses Poc?

Upvotes: 0

Views: 42

Answers (1)

SLaks
SLaks

Reputation: 887887

As the compiler is trying to tell you, you need to declare your function as being able to throw things using throws Exception.

In this case, you would want the abstract method to be able to throw.

Upvotes: 2

Related Questions