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:
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.compiling...
/home/sean/tmp/MissingReturnValue.java:17: missing return statement
}
^
1 error