Link to home
Start Free TrialLog in
Avatar of pgiusto
pgiusto

asked on

Throwing exceptions from static initialization code

I have a class that has a static initialization code and some static methods:

class X {

  static boolean Method1() {
    return var1;
  }

  static boolean var1;

  static {
     ...
     // initialization code that throws a Exception
     ...
  }
}

But I have no choice to catch the Exception. I have to throw it away.

¿ There is a way to declare that the static initialization code throws a Exception ?
ASKER CERTIFIED SOLUTION
Avatar of kotan
kotan
Flag of Malaysia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of selsted
selsted

If you want to throw an Exception, you need to write:

public static void X() throws Exception
{
  // Throws Exception
}

When you write "throws Exception", you are forced to make a try catch around your method calling X, or make that method throws Exception.

If you want to avoid writing throws Exception, throw a RuntimeException instead. This way, you are not forced to make a try catch.

public static void X()
{
  // Throws RuntimeException
}
> There is a way to declare that the static initialization code throws a Exception ?

what do you need this for ?
Avatar of pgiusto

ASKER

I need throwing a Exception, because the code effectively throws a Exception. Of course I can use a boolean variable and ask for that variable in every method of my class.
I ask the question because I didn't know if it was possible to throw a Exception from a static initialization block. If it's impossible, OK, let's find another way !!!

Thanks everybody.
you can always and everywhere throw RuntimeException (like NullPointerException)
And in this case it makes sense to throw
    ExceptionInInitializerError
like this...

-------StaticCode.java-------cut here-------8<-------
public class StaticCode
{
    public static final long[] a = new long[1];
   
    static
    {
        a[0]=Math.round( Math.random() );
       
        if (a[0]==0)
        {
            throw new ExceptionInInitializerError( "...is being thrown when a[0] is initialized to 0" );
        }
    }
   
} /* StaticCode */
-------StaticCode.java-------cut here-------8<-------


-------statictest.java-------cut here-------8<-------
public class statictest
{
    public static void main( String[] args )
    {
        System.out.println( "Start." );
        long a = StaticCode.a[0];
        System.out.println( "a="+a );
        System.out.println( "Done." );
    }
   
} /* statictest */
-------statictest.java-------cut here-------8<-------

Greetings,
    </ntr> :)