Search code examples
javaexceptionexit

Is it okay to exit code or should I terminate main?


I'm new to exception handling, and I don't know where to stop my code if something unexpected occurs.

I have a program dealing with command line arguments. I store the arguments with the values in a HashMap. And I have a method called getAlgortihm which should get the algorithm from the map. E.g.: arguments: -alg shift, the method returns shift. The value shift is necessary, because another method uses it to decide what to do next.

public String getAlgorithm() {
        return argumentMap.get("-alg");
}

Is it okay to exit the code if -alg is not given (arguments: -algWrong shift)?

public String getAlgorithm() {
        if (argumentMap.get("-alg") == null){
            System.out.println("-alg is not given");
            System.exit(1);
        }
        return argumentMap.get("-alg");
}

Or should I throw an exception and handle it where I call the method?

public String getAlgorithm() {
        if (argumentMap.get("-alg") == null)
            throw new NullPointerException("-alg is not given");
        return argumentMap.get("-alg");
}

Solution

  • It's poor programming practice to perform an exit from a function. It also makes testing such a function impossible.

    In cases like this, where you have an error in a function, you should throw an exception and then the calling code can handle it as needed. This also makes for testable code since your test can call and expect to get an exception which is the correct behavior in an error.