AndreaNobili
AndreaNobili

Reputation: 43027

How to handle fail situation into a simple Java application?

I am a Java developer but I have not yet got a lot of experience in software architecture.

I have the following situation. I am creating a batch application (a command line application that run into the shell) so it is started from a main() method defined into a Main() class.

Into this main() method I create some objects instances of other classes that do something (such as performing query on a DB, create PDF, etc) so here the application could fail.

If the application don't fail (everything went as expected) the main() method end with an exit code = 0.

I want that if the application fail (at any point) the returned exit code is -1.

So now I don't know how I have to handle this situation.

For example if into the main() method I have something like this:

// Create DAO object:
FatturaDAO fatturaDAO = new FatturaDAO(conn);
listaFatture = fatturaDAO.getListaFatturePDF(partitaIVA);

in which I create and use a DAO object. Considering now the case in which something fail into the FatturaDAO object (for example connection is lost and an exception is thrown).

How correctly handling this situation?

I have 2 ideas but I don't know what is the best solution:

  1. I put some try catch blocks inside my code so if something fails it enter into the catch block that handle it performing a:

    System.exit(-1);
    
  2. If something fail it enter into the catch block that instead of exit throws a custom exception that goes back until the main() method that perform:

    System.exit(-1);
    

Or maybe can I handle these situations in some other smarter way?

Upvotes: 1

Views: 110

Answers (2)

Rob Conklin
Rob Conklin

Reputation: 9479

In command line applications, the main() method is effectively the UI layer. It's a very bare-bones UI, but still, if you structure your app so that the main class is invoking a controller layer, and the controller layer is throwing an exception, you should catch that exception in the main() method, and return the correct "user value" of 0 or -1.

Upvotes: 1

atish shimpi
atish shimpi

Reputation: 5023

2. If something fail it enter into the catch block that instead of exit 
throws  a custom exception that goes back until the main() method that perform:

If you are handling exceptions in main() then you have to have error handling code at the parent level. If there's any change there's no need to check other functions, you just need to add the through keyword on the other functions and handle the exception in main() and return the required type.

In most J2EE applications we handle exceptions in the Controller part not the DAO or Service layers. It is easier to pass messages to users when exceptions happen.

Upvotes: 3

Related Questions