Static Initializer

Hi,
If a static initializer in MyClass throws an Exception, where do I have to declare a throws clause for it? When using MyClass elsewhere, how do I catch this exception? Where do I put the try-catch?
thanks

Short answer. You can't.
Read some of these.
http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2B%22static+initializer%22+%2Bthrow+%2Bexception&col=javaforums

Similar Messages

  • Help required on java.lang.StackOverFlowError and static initializer

    I wanted to create an instance of a class that contains another instance of the same class. So I wrote:
    class A {
         A z = new A ();     
         void display () {
              System.out.println ("Hello World");
         public static void main (String [] args) {
              A y = new A();
              y.display ();
    }During execution I got java.lang.StackOverFlowError. But if I put a static initializer, it works fine. Here is the code using static initializer.
    class A {
         static{
              A z = new A ();     
         void display () {
              System.out.println ("Hello World");
         public static void main (String [] args) {
              A y = new A();
              y.display ();
    }Could anyone please help me to understand the logic why "java.lang.StackOverFlowError" is happening here and how the same program runs fine by putting a static initializer ?
    Regards,
    Shambhu

    Could anyone please help me to understand the logic
    why "java.lang.StackOverFlowError" is happening hereWhen you instantiate an A object with A y = new A () then A z = new A () also gets executed inside the A class, which in it's turn executes A z = new A () again, and again, and again...
    and how the same program runs fine by putting a
    static initializer ?Because the static block gets executed only once.
    The use of class- and instance variables is explained in more detail here:
    http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html

  • JSP behavior - static initializer and jspInit

    In a recent discussion, the concept of using a static intializer in a JSP came up. The situtation was that someone had a series of Strings used in a single JSP and they wanted to #1, define these strings in the JSP itself (vs in web.xml or a resource file, which while preferable, was not really an item of discussion) and #2 wanted indexed access to the Strings (such as via a Map).
    My thought was to declare the Map variable as static final in the JSP and then initialize it in a static initializer block with Map.put operations. Both the declaration of the Map and the static initializer block would be declared in a <%! %> declaration tag block. (The thought behind the static initialization - vs overriding jspInit - being that if multiple instances of the JSP were to be created, we wouldn't want to keep put'ing values into the Map for each new instance of the JSP.)
    I built the following test scenario:
    <<untitled3.jsp source>>
    <%@ page import="java.util.*" %>
    <%!
    static final Map m = new HashMap();
    static int staticCount = 0;
    static int jspInitCount = 0;
    static {
    System.out.println("static initializer called");
    staticCount++;
    m.put("staticCount"+staticCount, "static# " + staticCount);
         public void jspInit() {
              super.jspInit();
    jspInitCount++;
    m.put("jspInitCount"+jspInitCount, "jspInit# " + jspInitCount);
    System.out.println("overriden jspInit called:" + this);
    %>
    Map values:<br>
    <%
    Collection values = m.values();
    Iterator i = values.iterator();
    while (i.hasNext()) {
    out.println(i.next().toString() + "<br>");
    %>
    Test
    <<end of untitled3.jsp source>>
    with the following web.xml entries:
    <servlet>
    <servlet-name>JSPServlet1</servlet-name>
    <jsp-file>untitled3.jsp</jsp-file>
    </servlet>
    <servlet>
    <servlet-name>JSPServlet2</servlet-name>
    <jsp-file>untitled3.jsp</jsp-file>
    </servlet>
    <servlet-mapping>
    <servlet-name>JSPServlet1</servlet-name>
    <url-pattern>/jsp1</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
    <servlet-name>JSPServlet1</servlet-name>
    <url-pattern>/jsp2</url-pattern>
    </servlet-mapping>
    I open a browser and request untitled3.jsp, I get the following output in the browser:
    Map values:
    static# 1
    jspInit# 1
    Test
    with the following output to my JDeveloper (9.0.3.1) log window:
    static initializer called
    overriden jspInit called:_untitled3@61
    I then request /jsp1 and get the following output in the browser:
    Map values:
    static# 1
    jspInit# 2
    jspInit# 1
    Test
    with the following output to my log window:
    overriden jspInit called:_untitled3@63
    Subsequent calls to /jsp1, /jsp2 or untitled3.jsp result in that same last output in the browser and no further output in the log window (ie, no further calls to the static initializer or jspInit method)
    So, it appears that jspInit is being called once for the unmapped JSP request and one more time, the first time one of the web.xml-mapped JSP instances is requested. (I'd have thought that it would be called once for the /jsp1 request and once for the /jsp2 request...), but the static initializer is being called only once as expected.
    Is this the correct behavior for the jspInit method? (ie, being called once for the unmapped request and once for the first mapped request?)
    Also, if OC4J is used in a clustered/balanced configuration, is it possible that I'd end up with additional instances of my JSP in one or more JVMs?
    Thanks!
    Jim Stoll

    You could scope such info to the application scope - some info is provided here: http://java.sun.com/products/jsp/tags/11/syntaxref11.fm14.html
    "application - You can use the Bean from any JSP page in the same application as the JSP page that created the Bean. The Bean exists across an entire JSP application, and any page in the application can use the Bean."

  • JNDI lookup in Static initializer

    Hi,
    Is there a problem looking up home interfaces in a static initializer in
    WL6.1?
    I have a class X which runs in my application client. It has a static
    initializer that looks up a home interface. The call to Context.lookup()
    times out with weblogic.rjvm.PeerGoneException: No message was received for:
    '240' seconds.
    The strange thing is, if I force the static initializer to run myself (by
    instantiating X directly), then it runs ok. I only get the above problem if
    the VM causes it to run (by loading a class Y that references X).
    Also, this behaviour is only apparent in the client. In the app server, X
    behaves correctly. I'm passing in JNDI properties as system properties on
    the command line to the client.
    Any help appreciated.
    Cheers,
    Manish

    Check the class loader and thread dump during the place where it works and
    the one where it doesn't ... that could help track down why it works that
    way.
    Peace,
    Cameron Purdy
    Tangosol Inc.
    << Tangosol Server: How Weblogic applications are customized >>
    << Download now from http://www.tangosol.com/download.jsp >>
    "Manish Shah" <[email protected]> wrote in message
    news:[email protected]..
    Hi,
    Is there a problem looking up home interfaces in a static initializer in
    WL6.1?
    I have a class X which runs in my application client. It has a static
    initializer that looks up a home interface. The call to Context.lookup()
    times out with weblogic.rjvm.PeerGoneException: No message was receivedfor:
    '240' seconds.
    The strange thing is, if I force the static initializer to run myself (by
    instantiating X directly), then it runs ok. I only get the above problemif
    the VM causes it to run (by loading a class Y that references X).
    Also, this behaviour is only apparent in the client. In the app server, X
    behaves correctly. I'm passing in JNDI properties as system properties on
    the command line to the client.
    Any help appreciated.
    Cheers,
    Manish

  • Problems with static member variables WAS: Why is the static initializer instantiating my class?!

    Hi,
    I have been hunting down a NullPointerException for half a day to come to
    the following conclusion.
    My constructor calls a method which uses static variables. Since an intance
    of my class is created in the static block when the class is loaded, those
    statics are probably not fully initialized yet and the constructor called
    from the static block has those null pointer problems.
    I've considered moving the initialization of the static variables from the
    declaration to the static block. But your code is inserted BEFORE any other
    code. Therefore not solving my problem.
    Two questions:
    1) what would be a solution to my problem? How can I make sure my static
    variables are initialized before the enhancer generated code in the static
    block calls my constructor? Short of decompiling, changing the code and
    recompiling.
    2) Why is the enhancing code inserted at the beginning of the static block
    and not at the end? The enhancements would be more transparent that way if
    the static variables are initialized in the static block.
    Thanks,
    Eric

    Hi Eric,
    JDO calls the no-args constructor. Your application should regard this constructor as belonging
    primarily to JDO. For example, you would not want to initialize persistent fields to nondefault
    values since that effort is wasted by JDO's later initilization to persistent values. Typically all
    you want to initialize in the no-args constructor are the transactional and unmanaged fields. This
    rule means that you need initialization after construction if your application uses the no-args
    constructor and wants persistent fields initialized. On the other hand, if your application really
    uses constructors with arguments, and you're initializing persistent fields in the no-args
    constructor either unintentionally through field initializers or intentionally as a matter of
    consistency, you will find treating the no-args constructor differently helpful.
    On the other hand, if Kodo puts its static initializer code first as you report, then it is a bug.
    Spec Section 20.16: "The generated static initialization code is placed after any user-defined
    static initialization code."
    David Ezzio
    Eric Borremans wrote:
    >
    Hi,
    I have been hunting down a NullPointerException for half a day to come to
    the following conclusion.
    My constructor calls a method which uses static variables. Since an intance
    of my class is created in the static block when the class is loaded, those
    statics are probably not fully initialized yet and the constructor called
    from the static block has those null pointer problems.
    I've considered moving the initialization of the static variables from the
    declaration to the static block. But your code is inserted BEFORE any other
    code. Therefore not solving my problem.
    Two questions:
    1) what would be a solution to my problem? How can I make sure my static
    variables are initialized before the enhancer generated code in the static
    block calls my constructor? Short of decompiling, changing the code and
    recompiling.
    2) Why is the enhancing code inserted at the beginning of the static block
    and not at the end? The enhancements would be more transparent that way if
    the static variables are initialized in the static block.
    Thanks,
    Eric

  • How to reference a static variable before the static initializer runs

    I'm anything but new to Java. Nevertheless, one discovers something new ever' once n a while. (At least I think so; correct me if I'm wrong in this.)
    I've long thought it impossible to reference a static variable on a class without the class' static initializer running first. But I seem to have discovered a way:
    public class Foo  {
      public static final SumClass fooVar;  // by default initialized to null
      static  {
         fooVar = new SumClass();
    public class Bar  {
      public static final SumClass barVar;
      static  {
         barVar = Foo.fooVar;  // <<<--- set to null !
    }Warning: Speculation ahead.
    Normally the initial reference to Foo would cause Foo's class object to instantiate, initializing Foo's static variables, then running static{}. But apparently a static initializer cannot be triggered from within another static initializer. Can anyone confirm?
    How to fix/avoid: Obviously, one could avoid use of the static initializer. The illustration doesn't call for it.
    public class Foo  {
      public static final SumClass fooVar = new SumClass();  // either this ..
    public class Bar  {
      public static final SumClass barVar = Foo.fooVar;  // .. or this would prevent the problem
    }But there are times when you need to use it.
    So what's an elegant way to avoid the problem?

    DMF. wrote:
    jschell wrote:
    But there are times when you need to use it. I seriously doubt that.
    I would suppose that if one did "need" to use it it would only be once in ones entire professional career.Try an initializer that requires several statements. Josh Bloch illustrates one in an early chapter of Effective Java, IIRC.
    Another classic usage is for Singletons. You can make one look like a Monostate and avoid the annoying instance() invocation. Sure, it's not the only way, but it's a good one.
    What? You only encounter those once in a career? We must have very different careers. ;)
    So what's an elegant way to avoid the problem? Redesign. Not because it is elegant but rather to correct the error in the design.<pff> You have no idea what my design looks like; I just drew you a couple of stick figures.If it's dependent on such things as when a static initializer runs, it's poor. That's avoidable. Mentioning a case where such a dependency is used, that's irrelevant. It can be avoided. I know this is the point where you come up with a series of unfortunate coincidences that somehow dictate that you must use such a thing, but the very fact that you're pondering the problem with the design is a design problem. By definition.
    Besides, since what I was supposing to be a problem wasn't a problem, your "solution" isn't a solution. Is it?Well, you did ask the exact question "So what's an elegant way to avoid the problem?". If you didn't want it answered, you should have said so. I'm wondering if there could be any answer to that question that wouldn't cause you to respond in such a snippy manner. Your design is supposedly problematic, as evidenced by your question. I fail to see why the answer "re-design" is unacceptable. Maybe "change the way the Java runtime initializes classes" would have been better?
    This thread is bizarre. Why ask a question to which the only sane answer, you have already ruled out?

  • Static initialization of java code included in the Imported Archives jars?

    Hi
    Does SAP PI 7.0 support static initialization of java code included in the Imported Archives jars?
    Static block of a java class included in the Imported Archive jars throws a Runtime Exception called ExceptionInInitializationError while trying to run.
    Regards,
    RDS

    Have you tested the code outside PI?

  • Static initializer error

    hi guys,
    can anyone explain what might cause the following error?
    i have the following classes
    class BonesPlayLevel {
    // execution reaches here
    ObjFigure.initJointedModel();
    class ObjFigure {
    public static void initJointedModel() {
    // execution does not reach here
    initJointedModelList(myVecs);
    and when i try and run i get the following error message:
    java.lang.Error: Static initializer: java.lang.NullPointerException
    java.land.Error
    cheers
    spob

    its ok i understand how to debug, and how the stack trace works.
    i am running this in JBuilder, here is the output produced
    D:\Nokia\Devices\Series_60_MIDP_Concept_SDK_Beta_0_3_1_Nokia_edition\bin\emulator.exe -classpath "E:\javaApps\MIDlets\mlj3d_exbones\classes;D:\MLJ3D\v1.0.1dev\jars\mljFrame.jar;D:\MLJ3D\v1.0.1dev\jars\mljRender.jar;" -Xdevice:Series_60_MIDP_Concept_SDK_Beta_0_3_1_Nokia_edition -Xdescriptor:"E:\javaApps\MIDlets\mlj3d_exbones\jad-temp\ExBones.jad"
    java.lang.Error: Static initializer: java/lang/NullPointerException

  • Instance initializer and static initializer blocks

    Hi guys,
    I read about the above mentioned in the JLS and also in a book before, but I still don't quite understand, what is the use of these. I sort of have a rough idea, but not exactly. I mean, what is the purpose of the instance initializer and static initializer blocks, how can it be useful? I understand I can execute pieces of code that will initialize instance and static variables accordingly, but how is it different then to using a constructor to initialize these fields? Are these pieces of code executed before any constructor is executed, or when otherwise?
    Sorry for my noob, I'm learning.
    PR.

    Static initializers are useful for initializing a class when the initialization is more complex than simply setting a single variable, or when that initialization can throw a checked exception.
    public class Foo {
      private static final Bar bar;
      static {
        try {
          bar = new Bar();
          bar.doSomeInitializationStuff();
        catch (SomeCheckedExceptionThatBarThrows e) {
          throw new ExceptionInInitializerError(e);
    }Here we could not do the two-step new Bar() + doSomeInit() stuff in the line where we declare the bar variable. Additionally, assuming that one or both of those can throw a checked exception, we could not do that on the declaration line; we need the static initializer to wrap that in the appropriate unchecked exception.
    This allows us to do more complex class initialization when the class is loaded than we could do with a simple variable initialization.
    Instance initializers are useful if you want to perform the same steps in every constructor and don't want to have to repeat the code in each constructor. Instance initializers are executed as the first step of each constructor (or maybe it's after any super() calls, I forget).

  • Help please with a Static Initializer for ImageIcons inside Jar Files

    At the moment I'm playing around displaying XML using A JTree
    I am subclassing DefaultMutableTreeNode, and want it to have some default Icons set up....
    Sort of like this:
    public class XNode extends DefaultMutableTreeNode
        public static final ImageIcon icon;
       public static ImageIcon getIcon()
            return XNode.icon;
    }The only thing is that for the life of me after trying various things and searching these forums and google:
    I can't work out how to write the static Initializer for the ImageIcon.
    The ImageIcon will need to be created using a URL, cos it will be inside my jar file.....
    the usual...
               URL url = this.getClass().getResource("/images/Exit16.gif");
               ImageIcon Icon = new ImageIcon( url );but I wanted these Icons to be class members..............
    Could someone help?
    }

    DrClap " I don't understand why you put Class.forName in there either"
    A: Because I don't really know what I'm doing.
    I will try that suggestion.
    At present I have this:
         static ImageIcon loadIcon;
         static
              try
                loadIcon = new ImageIcon( Class.forName("cis.editor.xml.nodes.AlNode").getResource("/images/Exit16.gif"));
              catch( ClassNotFoundException cnfe )
                   System.out.println("ClassNotFound: " + cnfe.getMessage() );
         public static final ImageIcon defaultIcon = loadIcon;
         static
              try
                loadIcon = new ImageIcon( Class.forName("cis.editor.xml.nodes.AlNode").getResource("/images/tree_folder_major.gif"));
              catch( ClassNotFoundException cnfe )
                   System.out.println("ClassNotFound: " + cnfe.getMessage() );
         public static final ImageIcon commentIcon = loadIcon;
    //.......... ANd so OnWhy? Because do far it was the only way I could get it to compile.
    And It works..
    However it's a real abortion.. codewise.
    I need to load about 16 Icons that the various subclasses can 'use'
    DefaultTreeCellRenderer - must do somethng similar because it has a bunch of Icons to "Pick from",
    Only How is that done 'properly' ?

  • Exception in static initializer

    Hi,
    I have one class with one static variable.
    I am initializing this variable in static initializer block. But while initializing, it is throwing some checked exception which I dont want to catch in block.
    Static initializer block doesn't support "throws", what should be done?
    Thanks

    hm..
    I think it depends on implementation.. etc
    Anyways, point is not where I should catch the
    exception. Point is, how can I throw the exception to
    caller when I am initializing static members. I don't think this makes sense! The 'caller' has to be the class loader so unless you are using your own class loader then you don't have any real choice.
    You could always wrap the exception in an un-checked exception and let the system handle it but this may just close the application anyway!

  • When trying to launch a Java preferences get this message:  Cannot launch Java application A static initializer of the main class threw an exception: java.lang.NullPointerException"

    I have an IMac 10.5.8 and I am having problems with Java. I have tried todownload Java for Mac OS X 10.5 Update 4 and it looks as if it is doingsuccessfully, but I cannot see where it has put it and get this message when trying to launch Java preferences:
    Cannotlaunch Java application
    A static initializer of the main class threw an exception:java.lang.NullPointerException"
    Couldyou please help?

    Hmm, only way I know would be a relatively painless Archive & Install, which gives you a new/old OS, but can preserve all your files, pics, music, settings, etc., as long as you have plenty of free disk space and no Disk corruption, and is relatively quick & painless...
    http://docs.info.apple.com/article.html?artnum=107120
    Just be sure to select Preserve Users & Settings.

  • Static initializer not invoked

    Why is the static initializer of B (in the example below) is not invoked?
    public class A {
         public static void m1() {
              System.out.println("static m1 in A");
    public class B extends A{
         static {
              System.out.println("static init B");
         public static void m2() {
              System.out.println("static m2 in A");
    public class Main {
         public static void main(String[] args) {
              B.m1();
    Surprisingly the console output is just 'static m1 in A'.

    Class B doesn't have a static method named m1(). But its superclass does, so it's that method that is called. (Static methods are not inherited.) To call a method of class A, it's only necessary to load class A.

  • Static initializer block

    use of static initializer block

    Going directly to the point aren't you?
    A ststic initializer block is used, well, to initializes static variable! It is called when the class is loaded.
    It is use like this.
    public MyClass {
       static {
          private int foo = 38;
       public static int getFoo() {
          return foo;
    }

  • Uncaught exception: Static initializer: java/lang/SecurityException

    So i'm trying to compile some code of a small game for Doja.
    The code compiles fine but when i load it in the emulator i get the following eror:
    Uncaught exception java/lang/Error: Static initializer: java/lang/SecurityException.
    Now i haven't seen that before. I looked into it and first i thought there must be some static initializer block in some class but there isn't.
    Now i'm kinda stumped. What else can be the problem?

    A security exception is usually thrown when you try to use some function of the API that you're not allowed to use.
    For example, if the user has not given your application permission to connect to the internet, but you try to do so.
    Sometimes this error can be resolved by turning on the appropriate option in the ADF file.
    Cheers,
    Sam

Maybe you are looking for