Java - What is the output: throw new exception

Question

What is the output of the following code.

import java.lang.ClassNotFoundException;

class SuperThrows {
  void hello() throws ClassNotFoundException {
    System.out.println(1);
    throw new ClassNotFoundException();
  }
}

class SubThrows extends SuperThrows {
  @Override
  void hello() {
    System.out.println(2);
  }
} 

public class Main {
  public static void main(String[] args) {
    new SubThrows().hello();

    try {
      new SuperThrows().hello();
    }
    catch(ClassNotFoundException cnfe) {
      System.out.println(3);
    }
    finally {
      System.out.println(2);
    }
  }
}


Click to view the answer

2
1
3
2

Demo

import java.lang.ClassNotFoundException;

class SuperThrows {
  void hello() throws ClassNotFoundException {
    System.out.println(1);//from w  ww .  j a  v a  2 s  .c om
    throw new ClassNotFoundException();
  }
}

class SubThrows extends SuperThrows {
  @Override
  void hello() {
    System.out.println(2);
  }
} 

public class Main {
  public static void main(String[] args) {
    new SubThrows().hello();

    try {
      new SuperThrows().hello();
    }
    catch(ClassNotFoundException cnfe) {
      System.out.println(3);
    }
    finally {
      System.out.println(2);
    }
  }
}

Related Topic