Exception in static block + re-instantiating

Hello All,
I have got a number of unit tests and one that is running is causing an exception in a static block of a class which is expected. It throws an ExceptionInInitializerError which I catch in the unit test.
But then another test is running using the same class and this time it should pass and create an instance of the same class as before.
But instead I receive a java.lang.NoClassDefFoundError with no class name. Why? Can't I instantiate a class again once the initialisation had failed?
Regards
Jonas

It's part of the VM Specification.
See [2.17.5 Detailed Initialization Procedure|http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#24237]
The first time,
10. Otherwise, the initializers must have completed abruptly by throwing some exception E. If the class of E is not Error or one of its subclasses, then create a new instance of the class ExceptionInInitializerError, with E as the argument, and use this object in place of E in the following step. But if a new instance of ExceptionInInitializerError cannot be created because an OutOfMemoryError occurs, then instead use an OutOfMemoryError object in place of E in the following step.After that,
5. If the Class object is in an erroneous state, then initialization is not possible. Release the lock on the Class object and throw a NoClassDefFoundError.

Similar Messages

  • Exception handling in static block

    How to handle and exception raised in static block, pls answer

    Yeah, you are right, but I was just quoting the example on how to use it.
    Now, come to your problem,
    1. Static blocks are executed first time, when a class is loaded, i.e. when first reference of class is made.
    2. So, handle the situation there.
    E.g.
    You have test class:
    public class Test {
         static{
              try{
                   String s = null;
                   File f = new File(s);
              }catch(Throwable ne)
                   System.out.println("Eror");
                   throw new RuntimeException(); // Or use Error depends on your implementation
         public static void abc(){
              System.out.println("Hello");
    Now,
    calling it from another class:
    public class Test1 {
         public static void main(String[] args) {
              try{
              Test.abc(); *// This is the first instance where class for Test will be load and hence the static block will be executed*
              }catch(Throwable th) // Or catch Error
                   th.printStackTrace(); // Do the handling
              System.out.println("Done");
    This is a standard practice. From static block, instead of throwing Error exception, use some of your inherited class from Error. (i.e. create a exception framework inside your application)
    Hope this explains my point.

  • Problem in static block execution

    Hi all
    i have a class which has a static block and a static method.For the first time i call the static method in the class its strange that its excuting a part of the static block and entering the method later and agian turning back to static block.
    but for the secon time when i call the static method in that class its fine that static block is not executed..
    here is the code of the class which contains static block and static method
    public class LogServices
    private static String propFilename="plas.properties";
    private static String file="vdvd";
    static
    System.out.println("Inside static block");
    try
    System.out.println("Inside static block of Plasma Log Services ");
              file=PropertyProvider.getProperty(propFilename,"Log4jprops"); // here i am calling another method in another class to get some string from properties
    System.out.println("\n File is ********************************** "+file);
    catch(Exception e)
    System.out.println("Exception encountered the following Exception ["+e.getMessage()+"]");
              System.out.println("Finished static block");
    public static Logger initLog()
    Logger logger=Logger.getLogger(PlasmaLogServices.class);
    System.out.println("File in method is:"+file);
    return logger;
    and in my main program i am calling this
    LogServices.initLog(); and the output i observed on the screen is
    Inside static block
    Inside static block of Plasma Log Services
    File in method is:vdvd
    File is ********************************** log.properties
    Finished static block
    if u look at the output after " Inside static block of Plasma Log Services" (part of static block) its enetering method where " File in method is:vdvd" is printed .
    After some debugging i came to know that if i remove the line
    file=PropertyProvider.getProperty(propFilename,"Log4jprops"); and replace it by file="log.properties";(mean hardcoded) then the static block executes and later that method executes.
    can any one pls help me in this regard???

    The first time you instantiate a class
    LogServices, it's static block is being
    executed.
    After you've instantiated the class, you call its
    static method.
    If you call the static method again, the
    LogServices have their static block already
    executed, so it won't be executed again.
    I think that the execution of static block and static
    method is not mixed, as you thought. I think it is
    rather a logging issue. Most loggers do not guarantee
    that logging-messages are output in correct order.
    Regards, TomHello sir
    tahnks for ur reply and i got that .the problem was in the propertyprovider class i had a static variable logger =PlasmaLogservices.initLog() ; and hence after that it was by passing to that static method and coming back again .
    thanks for looking in to this

  • Can we have try/catch in a static block in a class?

    hi All
    i have a question about put a try/catch block in a static block in a class to catch exceptions that maybe thrown from using System.xxxx(). in my custom class, i have a static block to initialize some variables using System.xxx(). in case of any error/exception, i need to be able to catch it and let the caller know about it. i tried to put a try/catch block in the static block, and tried to rethrow the exception. but it is not allowed, how would i handle situation like this? thanks for your help and advise in advance.

    You could just swallow the exception inside try/catch
    block, and instead of throwing it out, just set a
    static variable to allow checking from outside
    whether the initialization succeeded, or check within
    the constructor / methods of this class for
    successful initialization, and throw the exception
    then. You could even save that exception in a static
    variable for later.Ouch, ouch, you're hurting my brain. This would allow someone to ignore a (presumably) fatal error. Throw a RuntimeException as indicated. You can wrap a checked exception in an unchecked one if need be.

  • Foreach loop in static block won't compile

    When I try to compile this:public class TestEnum
      private static String[] numerals =
          {"einz", "zwei", "drei", "vier"};
      static
        for (String n : numerals)
          // doesn't matter what's in here
      public static void main(String[] args)
    }I get this exception:An exception has occurred in the compiler (1.4.2-beta).
    java.lang.NullPointerException
        at com.sun.tools.javac.comp.Lower.visitArrayForeachLoop(Lower.java:2269)
        at com.sun.tools.javac.comp.Lower.visitForeachLoop(Lower.java:2242)
        at com.sun.tools.javac.tree.Tree$ForeachLoop.accept(Tree.java:559)
        at com.sun.tools.javac.comp.Lower.translate(Lower.java:1580)
        at com.sun.tools.javac.tree.TreeTranslator.translate(TreeTranslator.java:51)
        at com.sun.tools.javac.tree.TreeTranslator.visitBlock(TreeTranslator.java:131)
        at com.sun.tools.javac.tree.Tree$Block.accept(Tree.java:497)
        at com.sun.tools.javac.comp.Lower.translate(Lower.java:1580)
        at com.sun.tools.javac.comp.Lower.visitClassDef(Lower.java:1645)
        at com.sun.tools.javac.tree.Tree$ClassDef.accept(Tree.java:409)
        at com.sun.tools.javac.comp.Lower.translate(Lower.java:1580)
        at com.sun.tools.javac.comp.Lower.translate(Lower.java:1594)
        at com.sun.tools.javac.comp.Lower.translateTopLevelClass(Lower.java:2438)
        at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:408)
        at com.sun.tools.javac.main.Main.compile(Main.java:523)
        at com.sun.tools.javac.Main.compile(Main.java:41)
        at com.sun.tools.javac.Main.main(Main.java:32)The same thing happens if I use foreach with a Collection instead an array. If I use an old-style for loop or Iterator in the static block, it compiles fine. I can also put the foreach loop in the main method, and it works. Is this a known bug?

    You guys rock. Thanks for finding this problem. I'll get it fixed.

  • Static block in superclass to initialize static members in subclasses

    I am trying to create several classes that are all very similar and should derive from a super class because they all have common members and are all initialized the same way. I would prefer every member of my subclasses to be static and final as they will be initialized once and only once. I can not figure out the best way to make this work. Here is an example (using code that does not work, but you can see what I am trying to do):
    class Super
        protected static final String initializedInEachSubclass;
        protected static final String alsoInitializedInEachSubclass;
        // these need to be accessed from anywhere
        public static final String initializedInSuperclass;
        public static final String alsoInitializedInSuperclass;
        // this static initialization block is exactly the same for every instance
        static
            // initialize these based on what the subclasses initialized
            initializedInSuperclass = initializedInEachSubclass + alsoInitializedInEachSubclass;
        private Super () {} // never instantiated
        public static final String getMoreInfo ()
            // the same for each instance
            return Integer.toString (initializedInEachSubclass.length ());
    class Sub1 extends Super
        static
            initializedInEachSubclass = "My String for Sub1";
            alsoInitializedInEachSubclass = "My Other String for Sub1";
        private Sub1 () {} // never instantiated
    }The problem with the above code is that the static block in Super uses static final variables that have not been initialized yet. I can't make Super abstract. If I initialize the final variables in Super, then I can not reinitialize them in Sub1. But if they are not final, then they could be changed after being initialized (which I would rather not allow). I could make everything protected and not final and then make public get... () methods, but I like accessing them as attributes. It seems like this should be possible, but everything I have tried has led me to a catch-22.
    Any ideas on how I can put all my redundant initialization code in one place but still allow the subclasses to initialize the static members that make each of them unique? I will be happy to clarify my examples if you need more information.
    Edited by: sawatdee on Jan 3, 2008 9:04 AM

    sawatdee wrote:
    I am basically trying to avoid having redundant code in several classes when the code will be exactly the same in all of them.That's the wrong reason to subclass. You subclass to express type specialization. That is, a Dog IS-A Mammal, but it's a special type of Mammal that implements certain common mammal behaviors in a dog-specific way. A LinkedList IS-A List, but in implements common list operations in linked-list-specific ways.
    I don't really need to have the static final members in a superclass (and I don't even need a superclass at all), but I don't know how else to execute a big static initialization block in several classes when that code is exactly the same in all of them. Without knowing more details about what you're trying to do, this sounds like a case for composition rather than inheritance. What's now your superclass would be a separate class that all your "sublasses" have a reference to. If they each need their own values for its attributes, they'd each have their own instances, and the stuff that's static in the current superclass would be non-static in the "subs". If the values for the common attributes are class-wide across the "subs", the contained former super can be static.
    public class CommonAttrs {
      private final String attr1;
      private final int attr2;
      public CommonAttrs(String attr1, int attr2) {
        this.attr1 = attr1;
        this.attr2 = attr2;
    public class FormerSub1 {
      private static final CommonAttrs = new CommonAttrs("abc", 123);
    ... etc. ..

  • Clarification regarding static blocks.

    I can understand from this about the static initialization block. I just need one clarification. What is the difference between the blocks with and without the 'static' keyword? For eg., the following code prints 'Hello'
    class ClassWithStaticBlock {
              System.out.println("Hello");
    public class StaticBlockTester {
         public static void main(String[] args) {
              new ClassWithStaticBlock();
    }If I modify the class ClassWithStaticBlock like given below, I receive the same output. So, what is the difference between the two?
    class ClassWithStaticBlock {
         static {
              System.out.println("Hello");
    }Thanks.

    The static block is only run upon loading of the class. Well, during the initialization phase of loading it, but it amounts to much the same thing. Non-static initiializers are run every time the class is instantiated. Try this
    class ClassWithInitializers {
      static {
       System.err.printlln("Loading class");
        System.err.println("Initializing");
      public static void main(String[] args) {
        new ClassWithInitializers();
        new ClassWithInitializers();
        new ClassWithInitializers();
        new ClassWithInitializers();
    }See any difference?

  • Error handling in static block

    Hello All,
    I have the following code
    static{
    abc();
    private static void abc() throws Exception{
    how do I throw error in static block because if I write
    static {
    abc() throws Exception;
    it gives error during compilation.
    How do I handle it.
    Sachin

    This is my code ...
    import java.io.FileInputStream;
    import java.io.*;
    import java.util.Properties;
    * @author sachin
    * This class is used setting the configurations
    public class Config{
         static String files_incoming;
         static String files_outgoing;
         static{
              try {
                   configurations();
              } catch (ICMSException e) {
                   LoggerCitiUtil.debug("Error in static block");               
         public static void configurations() throws ICMSException{
              Properties prop = new Properties();
              try{
                   Properties property = System.getProperties();
                   String systemPath = property.getProperty("MAIN_BASE_PATH");
              prop.load(new FileInputStream( systemPath + "bin/scp.ini"));
              }catch(IOException e){                 
                   LoggerCitiUtil.debug("File not loaded in Config class");               
              try{
    files_incoming=prop.getProperty("files_incoming").trim();;
    files_outgoing=prop.getProperty("files_outgoing").trim();;                                   
              }catch(Exception e){
                   LoggerCitiUtil.debug("Error in Config class");
                   e.printStackTrace();
    In the static block I want to throw new ICMSException(e);
    When I write this :
         static{
              try {
                   configurations();
              } catch (ICMSException e) {
    throw new ICMSException(e);
                   LoggerCitiUtil.debug("Error in static block");               
    But it gives unhandled Exception during compile time.
    Can anyone help me out ?.

  • Regarding static block

    Hi,
    I need to get two properties from the properties file and i will use these properties across the application,How can i write the util class which get the two properties and i can use acrross the application.
    Can i use the staic block in the util class ?
    Pls suggest me.
    Thanks
    crr

    I would use a util class to lazily load the properties file. You will need to handle certain IO exceptions when loading props, which is too much for a static block to handle properly. For example,
    public synchronized Properties getProps() {
        if(this.props == null) }
            loadProps();
        return this.props;
    }-cheng

  • [Problem reading a file in a static block of code]

    Hi all,
    I'm trying to use a static block of code in an abstract class (let's say for initialisation). In this block I'm trying to read some lines of text from a file, and some FileNotFoundException are thrown,
    java.io.FileNotFoundException: file:/home/tom/workspace/cryptanalysis/data/keys (No such file or directory)
    java.io.FileNotFoundException: file:/home/tom/workspace/cryptanalysis/data/french_words (No such file or directory)
    but all the paths are valid and the files exist as you can see:
    tom@javahouse ~ $ ll /home/tom/workspace/cryptanalysis/data/
    total 24K
    -rw-r--r-- 1 tom users 151 jan 3 23:26 french_frequences
    -rw-r--r-- 1 tom users 2,0K jan 4 17:21 french_texts
    -rw-r--r-- 1 tom users 11K jan 4 17:16 french_words
    -rw-r--r-- 1 tom users 159 jan 4 17:21 keys
    tom@javahouse ~ $ cat /home/tom/workspace/cryptanalysis/data/french_words
    LE
    DE
    UN
    ETRE
    ET
    A
    IL
    AVOIR
    NE
    JE
    SON
    QUE
    SE
    QUI
    CE
    DANS
    I really don't understand why those exceptions are thrown, if somebody
    could help it would be very nice. (It is for a crypto school project)
    Thanks in advance. (Sorry for my english 'cause I'm french)
    Here is a code snippet :
    // Path to this class:
    // /home/tom/workspace/cryptanalysis/utils/TextUtils.java
    public abstract class TextUtils {
         private static String PATH;
         public static String[] KEYS;
         public static String[] WORDS;
         public static String[] PLAINTEXTS;
         public static float[] FREQUENCES;
          * Init KEYS, WORDS, PLAINTEXTS, FREQUENCES, and PATH,
          * with the files in the data folder.
         static {
              String line;
              PATH = TextUtils.class.getResource("../data/").toString();
              System.out.println(PATH);
              // When PATH is printed, it looks like this /home/tom/workspace/cryptanalysis/data/
              KEYS = FileUtils.readFileContent(PATH + "keys"); // Here is the first exception
              WORDS = FileUtils.readFileContent(PATH + "french_words");// Here is the second
              PLAINTEXTS = FileUtils.readFileContent(PATH + "french_texts");// Here is the third
              FREQUENCES = new float['['];
              try {
                   BufferedReader reader = new BufferedReader(new FileReader(PATH + "french_frequences"));// And the fourth
                   while(null != (line = reader.readLine()))
                        FREQUENCES[line.charAt(0)] += Float.parseFloat(line.substring(1));
              } catch (Exception e) {e.printStackTrace();}
    // Path to this class:
    // /home/tom/workspace/cryptanalysis/utils/FileUtils.java
    public abstract class FileUtils {
          * Read the content of the file denoted by the given path and
          * return an array of Strings containing each line.
          * @param path
          * @return an array containing all the lines from the file
         public static String[] readFileContent(String path) {
              try {
                   String line;
                   Vector container = new Vector(100, 100);
                   System.out.println(path);
                   BufferedReader reader = new BufferedReader(new FileReader(path));
                   while(null != (line = reader.readLine()))
                        container.add(line);
                   return (String[])container.toArray(new String[container.size()]);
              }catch(Exception e) {e.printStackTrace();return null;}
         ....

    vous �tes le type bienvenu
    (thats bablefish for "you're welcome dude")Wow! That means "vous �tes bienvenu" means "You are welcome here" (i.e., "welcome at the forum", or whatever), not the proper answer to "Thank you".
    The shortest form of "You're welcome" in the sense you intended it is "De rien". [literally, "of nothing"--so it would be something like if you said in English, "It was nothing."]

  • What type of member is a static block?

    In the the first chapter of the Java programming language 4th addition it states the following
    A class can have three kinds of members:
    1)Fields are the data variables associated with a class and its objects and hold the state of the class or object.
    2)Methods contain the executable code of a class and define the behavior of objects.
    3)Nested classes and nested interfaces are declarations of classes or interfaces that occur nested within the declaration of another class or interface.And this got me thinking about static blocks. Which category do they fit into among the above? Are they really methods? I don't think so myself although inside they can look like a method implementation. Also, the same goes for constructors, in JLS doesn't it say these are not methods either? There is no mention of them above though.
    Anyone have any views/thoughts/explanation on the above?

    Section 8.2 of the JLS (http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.2) reads:
    <quote>
    The members of a class type are all of the following:
    * Members inherited from its direct superclass (�8.1.4), except in class Object, which has no direct superclass
    * Members inherited from any direct superinterfaces (�8.1.5)
    * Members declared in the body of the class (�8.1.6)
    Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.
    We use the phrase the type of a member to denote:
    * For a field, its type.
    * For a method, an ordered 3-tuple consisting of:
    o argument types: a list of the types of the arguments to the method member.
    o return type: the return type of the method member and the
    o throws clause: exception types declared in the throws clause of the method member.
    Constructors, static initializers, and instance initializers are not members and therefore are not inherited. [my emphasis]
    </quote>

  • How do I disable "Exceptions" button for "Block pop-up windows" in Content tab?. I am able to Disable other Exception buttons in this tab using about:config preference.

    Need a way to disable "Exception" button for "Block Pop-up windows" in Tools-> Options -> Content tab. I want to be able to do this for Locking Down Firefox preferences.
    == User Agent ==
    Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)

    That button doesn't have a pref associated with it, so you can't disable that button with a pref on the about:config page or a lockPref call.
    That only leaves the choice to remove that button with code in userChrome.css
    <pre><nowiki>#popupPolicyButton {display:none!important;}</nowiki></pre>
    See http://kb.mozillazine.org/Editing_configuration#How_to_edit_configuration_files

  • Exceptions in popup blocking not work good

    why sub-domains in exceptions in popup blocking not work? if i add a particular subdomain it works, but when i add an star in subdomain to do for all not work:
    *.mihanblog.com
    *.blogfa.com
    //// Please add image upload on post feature to Firefox's support ////
    //// Also add a suggestion forum to Firefox's support (like Chrome's forums) ////
    Thanks

    Do not add a * because Firefox doesn't support wildcard that way.<br />
    Just specify the domain to apply the exception to a domains and all sub domains.
    *Bug 336207 - Add wildcards to cookie exceptions list to permit subdomains if all cookies are blocked

  • Handling ABAP Exceptions in a Block

    Hi,
    If a background task calls an ABAP Class Method and that method throws a defined exception of type CX_BO_ERROR, I would expect to see a possible outcome for that exception that would allow me to handle the exception for the specific task. If I activate that outcome then an exception handling path will be displayed on the graphical representation which is taken if the exception is then raised by the method. If the outcome is disabled then the workitem goes to error.
    If I want to catch these exceptions (for multiple tasks) in an enclosing block in order to handle them in a single, standard way, how do I achieve that? It does not seem possible to simply define the exception type in the enclosing block and then activate it in order to then be able to automatically catch any exceptions of a particular type that have their outcomes disabled in their individual tasks. It would appear that I have to activate the outcomes for each task and then raise it during with a Process Control item on the exception handling path of the task. This seems to defeat the object of having exception handling at the Block level. Is my understanding correct or am I doing something wrong?
    Also, is it possible to capture the class exception object from the method call and store it in the Task Container (in order to get text & longtext details)?

    Thankyou for both of your responses.
    I understand that an individual ABAP Object or BOR method (call during an Activity) can raise an exception which can be handled as a separate outcome of that activity. However, if there are multiple Activity steps in the workfow that can all throw similar exceptions and I want to react to all of those exceptions in a uniform way, it seems excessive to have to handle each exception individually for each Activity in order to do the same thing (e.g. I may just want to send a standard email to someone or trigger another workflow event).
    I may have misunderstood things but I thought that the purpose of the Block step was to be used as a kind of TRY..CATCH mechanism that will allow exceptions to thrown to the Block by enclosed Activities without the need for enabling outcomes at the Activity level. I thought it would be possible for the exception type to be defined in the Block properties so that all exceptions of that type could be handled at a higher level by a single Block outcome (regardless of which enclosed Activity threw it). If this is the case then I do not see the point in having to define individual outcomes for each activity within the Block.
    That said, I cannot seem to get it to work without enabling the outcome for each activity and using a Process Control step to raise the exception to the Block (which seems to defeat the object because I have, in fact, just handled the exception!). The reason for my original posting is to verify whether or not what I am trying to do is possible and to find out what I doing wrong with regards to Block configuration.
    Kind Regards
    Simon.

  • Help required in understanding of static blocks in java

    Hi ,
    Can some one help me in understanding the difference between static blocks in java....also what is the difference in declaring some static variables in a class and and declaring some variables in a static block? From an architecture viewpoint when should one use static blocks in Java?

    Static blocks are piece of code that can beexecuted
    before creating an instance of a class.static blocks are executed once, when the class
    itself is loaded by the JVM. They are not executed
    before creating each instance of a class.
    For example whatever you include in the mainn method will be
    executed without you having to create the instanceof
    the class using the new operator. So you can saythe
    main method is a static block.main is not a static initialisation block but a
    static method. a special case static method at that -
    it is only executed when the containing class is
    specified as a parameter to the JVM. (unless you
    specifcally call it elsewhere in code - but that
    would be bad form).
    in answer to the original post, static variables
    belong to the class. each instance of the class share
    the same static variables. Public static vars can be
    accessed by prefixing them with the class name. A
    static initialisation block can be used to
    initialise static variables. Variables declared
    within the static initialisation block exist only
    within the scope of the block.
    e.g.
    public class Foo {
    static Bar bar;        // static member variable
    // static initialisation block
    static {
    // variable declared in static block...
    String barInfo =
    arInfo = System.getParameter("barInfo");
    // ... used to initialise the static var
    bar = new Bar(barInfo);
    So is the only purpose of static initialization blocks is to initialize static variables? Does the initialization of static variables inside a static block make any difference in performance? If yes , then how ?

Maybe you are looking for

  • Can we Install siebel crm latest version on Windows  7 (64 bit )

    Hai to all May i know the Latest Version of Siebel CRM ? Can we install Siebel Crm on windows 7 (64) bit operating system. And i downloaded some of the files from oracle e-delivery cloud. its and all jar files how can i convert into .Exe Files ? Can

  • ForEach iterator in parent child relation

    Hi, How can i use forEach to iterate parent child view object. Issue it is only able to fetch value of parent vo not child view object values, if I use af:iterator instead of af:forEach it works perfectly. So there is no issue with data. But I am not

  • Help me track my stollen ipod please!

    My ipod got stollen two days ago and i tried to track it but i think its not connected to an internet connection. So is there another way i can track my ipod without wifi ?

  • Add new selection criteria in program RHXHAP_APP_DOC_PREPARE_ORG

    Hi All, my requirment is related to HR program  RHXHAP_APP_DOC_PREPARE_ORG. The selection criteria in the program is Org.Unit. Now we want to add Per.area/E.Group/job/Position in the selection criteria. Copied. I have added them in the Seleciton scre

  • Change of name - can't access purchased songs

    Hi - Any advice welcome: I have purchased a lot of songs from itunes on line store - this was done using my previous married name and a different computer; I recently got divorced and I have a new computer (standard windows XP - sorry!) and have chan