Home > Software design >  How to make java recognize unreachable code and stop with compile errors
How to make java recognize unreachable code and stop with compile errors

Time:10-15

I'm working in a big legacy project and I'm still learning about clean code in java and trying to apply some good manners that I already know. Nevertheless, I tried to write a method like I write in others languages (like Rust), avoiding unnecessary variables, etc... But in this case below it can't compile it without the unreachable return null outside the try-catch block.

    private Inet4Address setServerAddress() {
        try {
            if (somethingTrue()) {
                return (Inet4Address) Inet4Address.getByName("127.0.0.1");
            }

            return (Inet4Address) Inet4Address.getByName(getIP4());
        } catch (UnknownHostException e) {
            System.out.println("Error at getting the server address from "  
                    "command line. ("   e.getMessage()   ")");
            System.exit(1);
        }

        /* Unreachable */
        return null;
    }

I choose to use the System.exit(1) because as this is the terminal part of the application, I wouldn't like to see a big java exception message, but only something that made sense for the user.

So my question is, how can I make javac understand that there isn't any case that this function won't return something. I really don't like to keep a return null in my code, even if it will never run.

CodePudding user response:

any advanced IDE such as Eclipse can show unreachable code as a warning after compilation that shows up in Problems tab. In addition a Eclipse SpotBug plugin static analysis tool can find more sophisticated cases.

CodePudding user response:

Calling System.exit() down in the bowels of your code makes it hard to reuse this method.

I would have this method throw an exception (you can simply not catch the UnknownHostException) and have a try-catch at the top level of your tool (I'm assuming that "this is the terminal part of the application" means that this is a command line tool?), probably in your main method.

That allows you to put a standard way of handling all run time errors in a single place.

The exception could be an unchecked exception, or if you want to make the API clearer, make a new checked exception.

  • Related