logo

CuriousTab

CuriousTab

Discussion


Home Java Programming Exceptions See What Others Are Saying!
  • Question
  • What will be the output of the program?
    public class X 
    {  
        public static void main(String [] args) 
        {
            try 
            {
                badMethod();  
                System.out.print("A"); 
            }  
            catch (Exception ex) 
            {
                System.out.print("B");  
            } 
            finally 
            {
                System.out.print("C"); 
            } 
            System.out.print("D"); 
        }  
        public static void badMethod() 
        {
            throw new Error(); /* Line 22 */
        } 
    }
    


  • Options
  • A. ABCD
  • B. Compilation fails.
  • C. C is printed before exiting with an error message.
  • D. BC is printed before exiting with an error message.

  • Correct Answer
  • C is printed before exiting with an error message. 

    Explanation
    Error is thrown but not recognised line(22) because the only catch attempts to catch an Exception and Exception is not a superclass of Error. Therefore only the code in the finally statement can be run before exiting with a runtime error (Exception in thread "main" java.lang.Error).

    More questions

    • 1. What will be the output of the program (in jdk1.6 or above)?
      public class BoolTest 
      {
          public static void main(String [] args) 
          {
              Boolean b1 = new Boolean("false");
              boolean b2;
              b2 = b1.booleanValue();
              if (!b2) 
              {
                  b2 = true;
                  System.out.print("x ");
              }
              if (b1 & b2) /* Line 13 */
              {
                  System.out.print("y ");
              }
              System.out.println("z");
          }
      }
      

    • Options
    • A. z
    • B. x z