Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Right way to code a static initializer with fatal error?

  1. #1
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Right way to code a static initializer with fatal error?

    Here's a Small C... I can never remember the rest ... it's an example of something that caught me out just now on another project. I'm initialising a static member with some code that throws Exceptions. I was at first surprised that the compiler demanded a return statement after the System.exit(), but then again it's a bit much to expect the compiler to know which methods never, ever return. Maybe in Java 8 there'll be an 'exit int' statement? I should be careful what I wish for.

    Anyways, here's a contrived example that demonstrates the issue, I'd be interested to know how other Java coders handle the failed static initialiser, and how I can avoid the bogus return statement javac demands.

    package com.javaprogrammingforums.domyhomework;
     
    public class MissingReturnValue
    {
      private final static int THE_ANSWER = theAnswer();
      private static int theAnswer()
      {
        try
        { /* imagine an exception here is a show-stopping disaster */
          return Integer.parseInt("42");
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
        System.exit(1);
        /* bogus return statement would go here */
      }
      public static void main(String[] args)
      {
        System.out.println("The answer is " + THE_ANSWER);
      }
    }

    Javac's output:
    compiling...
    /home/sean/tmp/MissingReturnValue.java:17: missing return statement
    }
    ^
    1 error
    Ah okay, I've just reaped the benefits of the SC... (still can't remember. Any chance of a link? Say for example to the right of Java Careers? It's an important idea I hadn't seen in Initials until I came to JPFs) and re-arranged my code so that I have a variable declared outside the try..catch block, assign it in the try clause and return that at the end of the method. The System.exit() goes inside the catch clause. It still seems slightly nasty, so I'll leave this as-is in the hope that someone else might have a superior technique.


  2. #2
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: Right way to code a static initializer with fatal error?

    Just for posterity / discussion, while I'm struggling to read a consensus while searching for views on this elsewhere, I noticed a Sun document I'd never seen before that Oracle says has "completed the EOL process", so I'm uploading it here:

    100PercentPureJavaCookbook-4_1_1.pdf

    7. Pitfall: Misuse of System.exit
    Explanation: The System.exit method forces termination of all threads in
    the Java virtual machine. This is drastic. It might, for example, destroy all
    windows created by the interpreter without giving the user a chance to record
    or even read their contents.
    Solution: Programs should usually terminate by stopping all non-daemon
    threads; in the simplest case of a command-line program, this is as easy as
    returning from the main method. System.exit should be reserved for a
    catastrophic error exit, or for cases when a program is intended for use as a
    utility in a command script that may depend on the programís exit code.
    So maybe I should think of a pattern that allowed me to detect failed static initialisation and exit gracefully? I can't think immediately what that would be...

  3. #3
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,170
    My Mood
    Hungover
    Thanks
    141
    Thanked 599 Times in 514 Posts

    Default Re: Right way to code a static initializer with fatal error?

    Thanks for the SSCCE. It went a long way to explaining what you meant.

    But yeah, there isn't a great way to get around this. A bogus return value at the end will shut the compiler up.

    Actually, now that I'm looking at it, why don't you just rearrange the order of returns and whatnot? Something like this:

      private static int theAnswer()
      {
     
        try
        { /* imagine an exception here is a show-stopping disaster */
     
        }
        catch (Exception e)
        {
          e.printStackTrace();
          System.exit(1);
        }
     
        return Integer.parseInt("42");
      }

    And yeah, System.exit() isn't exactly pretty. But if something is a showstopper, you might not have much of a choice. Just make sure the user knows what's going on.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  4. #4
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: Right way to code a static initializer with fatal error?

    rearrange the order of returns
    That is what I've done at the moment: declare a reference that will hold the return value, set it to null, try to instantiate the object and assign it to the reference if it works, return the variable at the end.

    This does look like the least bad option.

  5. #5
    Super Moderator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,235
    Thanks
    176
    Thanked 817 Times in 760 Posts
    Blog Entries
    5

    Default Re: Right way to code a static initializer with fatal error?

    Something similar to what's already been mentioned - create a Singleton class which encapsulates the static variable and its instantiation. Access the class (or singleton) via a static method which throws the exception (that can then be caught at Runtime)

    Edit: something like:
    public class Singleton{
        private Integer THE_ANSWER = null;
     
        private static Singleton singleton = null;
     
        public Integer getTheAnswer(){
            return THE_ANSWER;
        }
     
        private Singleton() throws Exception{
            THE_ANSWER = initialize();
        }
     
        private Integer initialize() throws Exception{
            Integer i = 0;        
            try{
                  /* do whatever to initialize i*/
            }catch(Exception e){
             throw e;
            }
     
            return i;
        }
     
        public static Singleton getInstance() throws Exception{
            if ( singleton == null ){
                 singleton = new Singleton();
            }
            return singleton;
        }
    }
    Last edited by copeg; September 27th, 2011 at 02:50 PM.

  6. #6
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: Right way to code a static initializer with fatal error?

    create a Singleton class
    Maybe what's causing me the problem today is trying to keep some expanding utility code all in a single class, which means my static code has access to all the static data members and constructors. If I split this code up, then you're right and the problem doesn't exist to the same degree.

Similar Threads

  1. [SOLVED] non static variable this cant be referenced from a static context
    By chronoz13 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: June 20th, 2011, 06:13 PM
  2. Error using public static double Method
    By stommy989 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: October 13th, 2010, 03:01 PM
  3. Replies: 10
    Last Post: September 6th, 2010, 04:48 PM
  4. [SOLVED] remembering the for loop initializer
    By lotus in forum Loops & Control Statements
    Replies: 13
    Last Post: July 17th, 2009, 11:29 PM
  5. Replies: 4
    Last Post: June 18th, 2009, 09:23 AM