-2

When I execute this code I get caughtjava.lang.CloneNotSupportedException as an output! Why doesn't the NullPointerException get caught?

package arrays;

public class NestedTry {
    public static void main(String s[])
    {
        try{
            try{
                throw new NullPointerException();
            }
            finally{
                throw new CloneNotSupportedException();
            }
        }
        catch(Exception e)
        {
            System.out.println("caught"+e.toString());
            //which excpetion will be printed here?? :P
        }
    }
}
Okku
  • 7,468
  • 4
  • 30
  • 43
hhsb
  • 560
  • 3
  • 23

1 Answers1

1

Simply beacuse finally block executes for sure.

try{
        throw new NullPointerException();
    }
    finally{
        throw new CloneNotSupportedException();
        }

In the above code first NullPointerException() gets thrown, but for this try, finally block is again throwing CloneNotSupportedException();

So ultimately

catch(Exception e)
 {
    System.out.println("caught"+e.toString());
    //which excpetion will be printed here?? :P
 }

The above catch instead of catching NullPointerException catches the finally block's CloneNotSupportedException and prints caughtjava.lang.CloneNotSupportedException.

AnkeyNigam
  • 2,810
  • 4
  • 15
  • 23