Exit after fatal exception in main function or lower in call hierarchy

user1939991 :

If I have a program that invokes a method which must terminate if a particular exception is thrown, should I design it such that the exception is passed up back to main so it can safely return, or should I handle the exception in the function and invoke System.exit(-1)?

Here is an example of what I mean by handling it in the function:

public class MyClass{
     public static void main (String[] args){
        myFunction(args);
     }
     public static void myFunction(String[] args){
          try{
              if(args.length == 0) 
                   throw Exception("Invalid Input");
          }catch(Exception e){
              System.out.println(e);
              System.exit(-1);
          }
     }
 }

Here is an example of what I mean by passing it up:

public class MyClass{
     public static void main (String[] args){
        try{
             myFunction(args);
        }catch(Exception e){ 
             System.out.println(e);
        }
     }
     public static void myFunction(String[] args) throws Exception{
         if(args.length == 0)
              throw Exception("Invalid Input");
     }
 }

Which way should be used in this situation?

Nathan Hughes :

There’s very little reason to call System.exit. Maybe if there was some disastrous condition where you wanted to stop the JVM immediately, it’s hard to imagine what it would be. So I would say, never call System.exit without some very specific requirement.

Set up a try-catch block in the main method, catch Throwable, and log it. That minimizes the exception-handling elsewhere in the program and encourages a fail-fast way of programming so that exceptions don’t get eaten and lost.

Alternatively, maybe you have a small Java program run from a shell script. You could let the main method throw Exception and let the shell script caller redirect stderr to a file. But using a real logger gives more control over rolling and purging, etc.

If you’re worried some error could be thrown that can’t be logged (maybe we’re out of memory and can’t log without causing another out of memory error), add the logging to the caller in addition to having the Java program do its own logging, as a precaution.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=108714&siteId=1