Link to home
Start Free TrialLog in
Avatar of Amulya
Amulya

asked on

How to exit from the code

I would like to test if a file exists, if it does not then inform the user and exit.
 For this i did the foll:
  File fil = new File(file1);
  if(!fil.exist())
   {
    JOptionPane.showMessageDialog(this,"File1 does not exist");
  // How to exit from the code..should it be return
 //is there soemthing similar to exit as in shell scripting?
}
Thank you
Avatar of kylar
kylar

System.exit(int exitCode);

Generally exitCode = 0 where the program sucessfully exits or -1 (or other error code) when it terminates abnormally.

Cheers,
Kylar
As said by kylar, System.exit( int ) method is used to terminate the program. the integer passed is the return code that is returned to the script/app that initiated this program.


-Viswa
If you want to just return from the method, but you don't want to kill your whole app, use:

if (fil.exists())
  return;
or you can throw an exception,

if (!fil.exists())
{
   throws new FileNotFoundException();
}
While system.exit(int) works fine i feel u shld create business exception and catch u from the calling program.this will help u to hv full control of ur code flow.
Pritam, generally speaking, it's considered bad to lock a question with an answer unless you are absolutely sure that your answer is exact. Otherwise, you should post a comment so that the question remains unlocked, since most experts won't look at questions that are locked. This also works since the asker can choose any comment made as an answer. Since your answer merely re-iterates what the other experts have commented, it would be considerate of you to change your answer to a comment.

Cheers,
Kylar
ASKER CERTIFIED SOLUTION
Avatar of SpideyMod
SpideyMod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial