krishna
krishna

Reputation: 53

Query in Exception Handling

I created the below code for understanding purpose.

In below code there is an error in try block so it should go to catch block and print 15 also as finally block is always executed we should also get 20. But in the output I am getting only 20 and not 15 in the output.

Kindly advise how why there is this descripancy.I am a begineer in Java. Also make any necessary changes in the program if needed to get both 15 and 20 as output.

package javaapplication91;

public class NewClass 
{
public static void main(String[] args)
{
    NewClass n = new NewClass();
    int z = n.m1();
    System.out.println("z = " + z);
}

public int m1()
{
    try
    {
        int a = 10/0;
        System.out.println("Exception created");
        return 10;
    }
    catch(ArithmeticException ae)
    {
        return 15;
    }

    finally
    {
        return 20;
    }
}
}

Upvotes: 0

Views: 44

Answers (2)

MSD
MSD

Reputation: 1407

The return inside the ArithmeticException  will be overridden by the finally return and that will be returned to your function. Advice is , finally can be used only when closing a file or recovering resources.

Upvotes: 0

Aleksandr Podkutin
Aleksandr Podkutin

Reputation: 2580

You can return only one value from method if your method declaration return value type is int.

When you cath exception ArithmeticException you try to return 15, but you got 20, because finally block execute allways in the end of try catch block and it would be last return statement.

You can read about finally here (Java Tutorial)

If you want return both values, you can use array or list like this:

public List<Integer> m1() {

    List<Integer> returnValues = new ArrayList<Integer>();
    try {
        int a = 10/0;
        System.out.println("Exception created");
        returnValues.add(10);
    } catch(ArithmeticException ae) {
        returnValues.add(15);
    } finally {
        returnValues.add(20);
        return returnValues;
    }
}

Upvotes: 1

Related Questions