Is System.exit() a good call to use?

I have a program that checks for updates in the db. If there are no updates in the database I want the program to stop. There are also many other conditions that would cause the program to stop. None of them are "Errors" so I wasn't using Exceptions to end the program The program runs from a command line or from chron job. Is it safe / OK to use System.exit() to do this?

As you describe it, I'd say yes. System.exit() is the way to end your program.
The danger of System.exit() is if a class you write will be reused in some other system. In that case, System.exit() could be entirely inappropriate in that context, thus preventing your class from being reusable.
If you only call System.exit() in your main() method, you'll probably be OK.

Similar Messages

  • Error in XMLDiff Bean, System.exit() is being called in setFiles() ?

    When I call the setFiles() method in XMLDiff and the files contain dtd references, my application will shut down competely as though System.exit() is being called from within the XMLDiff bean. I have tested this with the XMLDiff demo and it also shut down when a dtd reference was in the files.

    The version of XDK is 9.2.0.2.0
    The test case is the "family.xml" in the demo\java\parser\common directory using the XMLDiffSample application. What I did was to try to compare the family.xml against itself. When I do that it shuts down the demo application as though System.exit() has been called.
    Setting the standalone="yes" did in fact cause it to work properly, but I am not sure why?

  • System.exit(int) and javac def-use calculation

    I'm wondering if anyone can tell me why javac (J2SE v1.4.2) seems to ignore "System.exit(int)" (alternately, "Runtime.getRuntime().exit(int)") for the pursposes of determining possible variable access before an initialization.
    For example, consider the following code:
    /*01*/  public class C {
    /*02*/    public void foo() throws Exception {
    /*03*/      C obj;
    /*04*/      while (true) {
    /*05*/        try { obj = new C(); }
    /*06*/        catch (Exception fault) { System.exit(1); }
    /*07*/        obj.foo();
    /*08*/      }
    /*09*/    }
    /*10*/  }Compile this (ignoring the absurdity of what "foo()" actually does), and you will get a variable obj might not have been initialized error. This despite the fact that a call to "System.exit(int)" never returns normally, by definition. To illustrate why this error doesn't make sense, substitute the "System.exit(1)" of line #6 with any of "break", "return", or "throw new Exception()". The use calculation for variable 'obj' is correct in these three alternate situations, but not for the first, even though the situation is analagous.
    Obviously, there is an easy work-around to this (viz., change line #3 to "C obj = null;"), though it seems unnecessary. Any ideas?

    System.exit() doesn't have the same "special" meaning
    to the compiler as "break", "return", or "throw" do.
    As far as the compiler sees, you are simply calling a
    method in your exception handler; it doesn't know
    that there will be no return from that method. Sure,
    the compiler could special-case System.exit(), but
    then you'd still see this same problem if you came up
    with your own wrapper method that calls
    System.exit().. the compiler in general doesn't (and
    shouldn't) assume that a method call will terminate
    the app.I understand that "System.exit(int)" is merely a method from the perspective of the compiler, but it is a rather special method (actually the "Runtime" version, for which the "System" version is merely a wrapper) with respect to correct program execution, calculated during the various traces that are done during compilation. And wrapping "System.exit(int)" with another method wouldn't make any difference to the calculation if it was considered, from the perspective of compilation, an uncaught (implicitly declared non-Runtime) exception. Besides, there must be some execution sequence within "Runtime.exit(int)" that serves, essentially, the same function as an "exit" keyword.
    What's wrong with supplying a default value when you
    declare the variable?Absolutely nothing, except that it isn't necessary. I typically do so anyway, and only came across this "feature" of javac during a lapse of my coding standards.

  • Disabling System.exit() and shutdown calls

    I am trying to splice/hack together something that might stop a System.exit(0) call or perhaps some type of exit call for a Java application. The only thing I have come up with now is making an extension of SecurityException and putting the shutdown code within a try. Here is what I have so far...
    class ExitTrappedException extends SecurityException {
         protected static void forbidSystemExitCall() {
              final SecurityManager securityManager = new SecurityManager() {
                   public void checkPermission( java.security.Permission permission ) {
                        if( "exitVM".equals( permission.getName() ) ) {
                             throw new ExitTrappedException() ;
              System.setSecurityManager( securityManager ) ;
         protected static void enableSystemExitCall() {
              System.setSecurityManager( null ) ;
    }And then utilizing it in the following manner...
    forbidExitCall() ;
        try {
          // Call the "exiting" code here...
        } catch( ExitTrappedException e ) {
        } finally {
          enableExitCall() ;
        }I am not very comfortable setting the SecurityManager to null when re-enabling it to be honest. I am curious if someone might have a different solution to stopping a System.exit(0) call and the windows altf4+ shortcut. Any help would be much appreciated.

         static SecurityManager securityDefault = System.getSecurityManager();
         protected static void forbidSystemExitCall() {
              final SecurityManager securityManager = new SecurityManager() {
                   public void checkPermission( java.security.Permission permission ) {
                        if( "exitVM".equals( permission.getName() ) ) {
                             throw new ExitTrappedException() ;
              System.setSecurityManager( securityManager ) ;
         protected static void enableSystemExitCall() {
              System.setSecurityManager( securityDefault ) ;
    }how bout that?
    Edited by: brillohead on Aug 4, 2008 11:21 AM

  • How  to track System.exit(0) call

    hi there,
    how can i trace the System.exit(0) function call in my program.
    i.e as we know which class is being loaded into the jvm by overriding
    the classloader, can we similarly know when is our jvm going to be
    destroyed. here iam invoking jvm from my windows program using invocation api.
    any help is mostly appreciated.
    thanks in advance
    bye
    ramana

    Not sure I know what you are asking.
    You could create a security manager which prevents exit() from being called.
    You could replace System using the bootstrap command line option. Although if you do that you can not distribute it due to the license agreement. Once replaced you can do anything you want in the application.
    You could use Runtime.addShutdownHook() if you just want to do something when the application exits.

  • How do I exit a java program based on condition can i use system.exit

    I have java program that is called by another program that I dont have control on. My program returns a bigdecimal... but if the ordernumber is empty in my program i dont wnat to do anything.. does system.exit work in that condition... i put it int he else if ordernumber is empty condition.. but i dont think that is the right approach..

    When software module is expected to bring some result, it should bring the result, positive or negative. I think you should check what your counterpart software expects as positive or negative result. And then implement your software this way. You can use System.exit, but this call is employed usually to indicate status with the software after it's completion and not to return any resulting value.
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#exit(int)

  • Why isn't System.exit(0) used from an Applet

    I am trying to figure out why the System.exit(0) method isn't used for an applet. Is it because an applet isn't an application (which is why the public static void main(String args[]))?
    I have noticed when if I include System.exit(0) I will get an compilation error.
    Is there someplace in the Java Tutorial that explains this?
    thanks

    You can put it in, but if you run it in a browser, it
    will kill the browser and all its windowsThat is if the applet is signed. I have also noticed this behaviour and I think it is pretty weird. It looks like a bug to me.

  • To trap System.exit(0)

    Hi All,
    In one of our code we are saying System.exit(0),System.exit(1),System.exit(-1) based on certain condition that occur in the program. Could any one let us know how to trap the integer returned to the OS when System.exit(x) is called.
    Regards,
    Vinodramu

    Not sure I know what you are asking.
    You could create a security manager which prevents exit() from being called.
    You could replace System using the bootstrap command line option. Although if you do that you can not distribute it due to the license agreement. Once replaced you can do anything you want in the application.
    You could use Runtime.addShutdownHook() if you just want to do something when the application exits.

  • System.exit() causes Firefox to close

    Hi.
    I have a strange problem - I have an app which can be both an applet and a standalone application. At some point is calls System.exit() and it can happen in an applet too. (It's easy to redesign the code but that;s not my question)
    Strange enough (for me at least) the call causes the whole browser to close! (Observed in FF 1.5.x and 2.0, reported in IE7). Is this supposed to happen?
    Thanks.

    No, this isn�t a bug. You should not call System.exit from an applet, instead use the life cycle methods of the Applet class.

  • System.exit(o) in Swing

    Hi,
    In my Swing application, as soon as I start the main() method, a dialog containing Username and Password fields with OK and Cancel buttons gets popped-up. I have a propertyChangeListener which gets notified when Ok or cancel is pressed and when Cancel is pressed, System.exit(0) is called to exit the JVM.
    So, there are two threads running -
    One - the main thread which invokes the dialog pop-up
    Second - the propertychangelistener which calls the System.exit(0) on pressing Cancel button.
    So, at times, after pressing cancel button, the application does not exit but invokes the previously running thread (main thread). But this does not happen always.
    Could you please let me know why the application does not terminate completely and how to resolve this?
    Thanks in advance!

    Hi,
    As I had already mentioned in my previous post -
    Here is the pseudo-code which fails to terminate on pressing Cancel button at times.
    ================The Login dialog code=============
    public LoginDialog()
    // Other code
    JOptionPane optionPane = new JOptionPane(array, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null, options, options[0]);
    optionPane.addPropertyChangeListener(new PropertyChangeListener()
    public void propertyChange(PropertyChangeEvent e)
              Object value = optionPane.getValue();
              if (value.equals(YES))
              else
    // user closed dialog or clicked cancel
    setVisible(false);
    System.exit(0);
    ===============The main thread===================
    This main() method calls the logindialog with username and passwrd as parameters.
    So, initially, the main() thread is started and the login dialog is displayed. On pressing Cancel in this dialog, the control goes to propertyChangeListener of the loginDialog() and calls System.exit(0) which should terminate the entire application, but at times, the previously running main thread is resumed and the application is not terminated.
    Please clarify why this happens.
    Thanks in advance!!
    });

  • Kill and System.exit

    Is there a way (with Linux) to issue the kill command on your java process so that System.exit(0) is called and you know that your shutDownHooks will run?

    Thanx again for the reply, Freddy
    first things first:
    System.exit(0) does not work in this case..
    and the code is reached..
    // main class
    public class AdminApp {
    public AdminApp() {
    public static void main(String[] args) {
    AdminApp adminApp1 = new AdminApp();
    AdminFrame frame = new AdminFrame();
    /// admin frame class
    public class AdminFrame extends JFrame{
    public AdminFrame() {
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    this.pack();
    this.setSize(600,480);
    this.setVisible(true);
    groupsMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    desktop.add(new AdminGroups());
    //admingroups class
    public class AdminGroups extends JInternalFrame {
    private JTextArea textArea = new JTextArea();
    private JScrollPane scrollPane = new JScrollPane();
    JPanel groupPanel = new JPanel();
    XYLayout xYLayout1 = new XYLayout();
    public AdminGroups() {
    setSize(200,300);
    setTitle("Edit Text");
    setMaximizable(true);
    setIconifiable(true);
    setClosable(true);
    setResizable(true);
    scrollPane.getViewport().add(textArea);
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(scrollPane,BorderLayout.CENTER);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    getContentPane().add(groupPanel);
    private void jbInit() throws Exception {
    groupPanel.setLayout(xYLayout1);
    }

  • The ABAP call stack was: SYSTEM-EXIT of program BBPGLOBAL

    Hi
    We are using SRM 5.0. We are facing a strange problem. We are able to see the initial screen of SRM EBP in the browser. But once the user name and password are provided the system goes for a dump with the following error:
    The following error text was processed in the system SS0 : System error
    The error occurred on the application server <Server Name> and in the work process 0 .
    The termination type was: ABORT_MESSAGE_STATE
    The ABAP call stack was: SYSTEM-EXIT of program BBPGLOBAL
    <b>SM21 Log:</b>
    Short Text
         Transaction Canceled &9&9&5 ( &a &b &c &d &e &f &g &h &i )
         The transaction has been terminated.  This may be caused by a
         termination message from the application (MESSAGE Axxx) or by an error
         detected by the SAP System due to which it makes no sense to proceed
         with the transaction.  The actual reason for the termination is
         indicated by the T100 message and the parameters.
    Transaction Canceled ITS_P 001 ( )
    Message Id: ITS_P
    Message No: 001
    I just checked these threads but did not help much,
    RABAX_STATE  error after loggin into BBPSTART service in SRM 4.
    ITS_TEMPLATE_NOT_FOUND error
    Besides I tried this note: 790727 as well, still I get the same error.
    Any help would be highly appreciated.
    Thanks in advance
    Kathirvel Balakrishnan

    Hi
    <u>Please do the following steps.</u>
    <b>When you are using the Internal ITS,you need not run the report W3_PUBLISH_SERVICES.(only SIAC_PUBLISH_ALL_INT )
    ALso pls check the foll:
    -->activate the services through SICF tcode.
    > Go to SICF transaction and activate the whole tree under the node Default host>sap>bc>gui>sap>its.
    >Also maintain the settings in SE80>utilities>settings>internet transaction server-->test service/Publish. (BBPSTART , BBPGLOBAL etc)
    Table TWPURLSVR should have entries for the / SRM server line as well as gui and web server.
    Could you please review again the following steps ?
    Did you check that ICM was working correctly (Transaction -  SMICM) ?
    1-Activate the necessary ICF services
    With transaction SICF and locate the
    services by path
    /sap/public/bc/its/mimes
    /sap/bc/gui/sap/its/webgui
    2- Publish the IAC Services
    With Transaction SE80 locate from
    the menu Utilities -> Settings ->
    Internet Transaction Server (Tab) ->
    Publish (Tab) and set “On Selected
    Site” = INTERNAL.
    3- Locate the Internet Services SYSTEM and WEBGUI.
    Publish these services with the Context
    Menu -> Publish -> Complete Service
    4- Browse to http://<server>:<icmport>/sap/bc/gui/
    sap/its/webgui/! and login to the
    webgui.</b>
    Hope this will help.
    Please reward suitable points.
    Regards
    - Atul

  • How stop call to System.exit but allow them to install Securitymanager?

    I have an application that allows you to start a java application from inside it (it then gives you monitoring capabilities). I want this to work with pretty much any desktop application, even those that require their own security manager. However, i don't want their application to be able to shutdown the jvm. How can I do this?
    As far as I can tell, there's no way to allow them to add the securitymanager, "wrapped" by mine is there?
    And I thought of using AccessController.doPriviledgedAction(...) and giving them a context where they can add a security manager but not call system.exit, but then if they do add a security manager, won't it have the final say on system.exit calls?
    Is there a solution here?

    6tr6tr wrote:
    Thanks for the reply!
    Hmmm, the problem with that is I need the users to be able to use my application without access to that app's source code. So they need to be able to run that program (as 3rd party black-boxed code) inside my app and still have this work properly. Is there another way?
    Source code?
    You don't need any source code for what I suggested.
    If a frame/jframe tries to exit on close, I can grab and stop that. my problem is if some random code tries to call system.exit(). Is there any other way to intercept it?
    UPDATE: the only solution i could come up with is to use bytecode engineering + classloading.
    Which I doubt will help if they call it with reflection.
    You could use the bootstrap command line options and replace System with your own version. Add some functionality to how it sets up the security manager and/or make System.exit() do nothing, but provide another name for yourself.

  • Problem using System.exit()

    Hai,
    I used System.exit(1) system call in my servlet code. When this part of code is executed the whole server goes down.. i need to know if there is another smooth way of exiting code instead of System.exit().
    Thanks

    is another smooth way of exiting code instead of System.exit().System.exit() is supposed to terminate the JVM....however, your server (especially I have seen Tomcat 4.x) can hang if you call System.exit()...because there may be some active threads still running in the JVM, and server is not able to terminate them...and gets stuck.
    What is your intent? If you want to cleanly shutdown the server, then don't call System.exit(), instead, the server listens on some port for commands, connect to that port and issue a quit/exit command. For example, in tomcat looking at server.xml you could look at this element <Server port="8005" shutdown="SHUTDOWN" debug="0">. Connect to port 8005 and issue "SHUTDOWN" command to gracefully terminate the Server.
    -BJ

  • Intercepting System.exit() and System.out.println() calls

    hi there,
    I have often problems when working with code that uses System.exit() and System.out.println() extensively, because it becomes difficult to debug.
    Basically I do have wrappers for System.exit() (my own static exit function) and for System.out.println() (log4j).
    Still not all programmers are using these methods; Probably the only way to enforce this is some kind of code warrior, but I was hoping to be able to intercept the two System.XXX calls (and throw an appropriate Exception). is this possible ??

    Why not simply make your own security manager andhandle checkExit() and checkWrite?
    Does anyone have a simple example of this? Please?System.exit() can be intercepted using a security manager, but not System.out.xxx.
    Here is a short example:
    //set your security manager
    static{
         SecurityManager s = new OwnSecurityManager();
         System.setSecurityManager(s);
    //redirect the out stream
    try{
         PrintStream ps = new PrintStream(new FileOutputStream("output.txt"));
         System.setOut(ps);
    }catch(IOException ioe){
         ioe.printStackTrace();
    //some tests
    System.out.println("Test");
    System.exit(2);
    //your security manager
    class OwnSecurityManager extends SecurityManager{
         public void checkExit(int code){
           if(code > 0){
             super.checkExit(code);
             throw new SecurityException("Not allowed here->" + code);
         public void checkRead(FileDescriptor fd){
         public void checkRead(String file){
         public void checkRead(String file, Object context){
         public void checkPermission(Permission perm){
           if(perm.getName().equals("exitVM")){
             System.out.println("exitVM");
    }

Maybe you are looking for

  • R/3(Idoc)-XI-R/3 (Idoc)

    Hello, I'm having some issues with sending IDOC from one system to another system via XI.  Both of these systems are R/3 6.20. I've pasted the trace output.  Can someone please help me identify the problem. Thanks Mohammed   <Trace level="1" type="T"

  • Windows Media Player for Mac issue

    Lately, and I not sure when it started. When I goto a radio station's website who offers streaming of their broadcasts, I click on the link, WMP opens and starts playing (although there is a delay). In the activity viewer of Safari, I see that their

  • What settings work in Health app without third party apps, iPhone 5s

    IM looking my for the settings in health that work without third party apps on iPhone 5s.

  • Transmiting video captured from a webcam to another system on Intranet

    Hi Everybody, Need your help. I have created an application in SWINGS which transmit my live webcam video to client in the intranet and the clients receive the live webcam Video. Now I have modified my code to run the same thing in Applets i.e. in fo

  • VBA dialog box hidden behind EPM processing window

    I have a BPC 10 report where I want to validate selections made by the user before refreshing.  I wrote a simple piece of code to test using one condition.  If the condition is met, I want to display a message and prevent the report from refreshing.