weird problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ashok2006
    New Member
    • Sep 2006
    • 5

    #1

    weird problem

    import java . io . * ;

    class Test {
    {
    try
    {
    throw new Exception ( ) ;
    }
    catch ( IOException e )
    {
    System . out . println ( e ) ;
    }
    }

    Test ( ) throws Exception{ } // Comment this line

    public static void main ( String args [ ] ) throws Exception {
    System . out . println ( " GodSmack " );
    }
    };

    Above program compiles and run fine
    but when I comment following line

    Test ( ) throws Exception{ } // Comment this line

    It gives me follwing compiler error

    unreported exception java.lang.Excep tion; must be caught or declared to be thrown
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    In your code the try block gets executed whenever a new TestA object is created. So creating a new TestA object can throw an exception as far as the compiler is concerned. Any attempt to create the TestA object should therefore be declared as throws exception. If you comment out that line, then construction of TestA objects is only allowed in contexts which have been declared as throws exception as you have done in the main so it compiles.

    The reason why the try/catch is always excuted in this case is the presence of the {} surrounding the it. Try for example running this


    Code:
    class TestB {
    {
           System.out.println("!!!!!!!!");
    }
           TestB(){}
           public static void main (String args []) throws Exception {
                System.out.println (" GodSmack ");
                new TestB();
         }
    }

    Comment

    • D_C
      Contributor
      • Jun 2006
      • 293

      #3
      Just FYI, you are throwing Exception and catching IOException. Since IOException is more specific than Exception, it will not catch Exception. However, if you throw IOException and catch Exception, it will catch it.

      Since you technically aren't catching the Exception you throw, you need to report that you throw Exception.

      Comment

      Working...