Boardy
Boardy

Reputation: 36237

Throwing Exception back to the calling method

I am working on an android project and I am trying to figure out how to throw an exception back to the calling thread.

What I have is an activity, and when the user clicks on a button it calls a threaded function within another java class (not activity, standard class). The method within the standard class can throw an IOException or Exception. I need to throw the exception object back to the calling method within the activity so that the activity can do some stuff based on what the exception was returned.

Below is my activity code:

private void myActivityMethod()
{
    try
    {
        MyStandardClass myClass = new MyStandardClass();
        myClass.standardClassFunction();
    }
    catch (Exception ex)
    {
        Log.v(TAG, ex.toString());
        //Do some other stuff with the exception
    }
}

Below is my standard class function

private void standardClassFunction()
{
    try
    {
        String temp = null;
        Log.v(TAG, temp.toString()); //This will throw the exception as its null
    }
    catch (Exception ex)
    {
        throw ex; //Don't handle the exception, throw the exception backto the calling method
    }
}

When I put throw ex in the exception, Eclipse seems to be unhappy, and instead asks me to surround the throw ex within another try/catch, which them means, if I do this, the exception is then handled within the second try/catch not the calling methods exception handler.

Thanks for any help you can provide.

Upvotes: 0

Views: 32890

Answers (2)

vipul mittal
vipul mittal

Reputation: 17401

Change:

private void standardClassFunction()
{
    try
    {
        String temp = null;
        Log.v(TAG, temp.toString()); //This will throw the exception as its null
    }
    catch (Exception ex)
    {
        throw ex; //Don't handle the exception, throw the exception backto the calling method
    }
}

to

private void standardClassFunction() throws Exception 
{

        String temp = null;
        Log.v(TAG, temp.toString()); //This will throw the exception as its null

}

If you want to handle the exception thrown in called function inside calling function. You can do by just not catching it rather throwing it as above.

Also if it is a checked exception like NullPointerException you don't even need to write throws.

More about checked and unchecked exceptions:

http://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/

Upvotes: 5

Tal
Tal

Reputation: 700

as mentioned above, when you declare throws in the method signature, the compiler knows that this method may throw an exception.

so now when you call the method from the other class, you'll be asked to surruond your call in try/catch.

Upvotes: 2

Related Questions