System.exit( int )

What is the difference between System.exit( 0 ), System.exit( 1 ), System.exit( 2 ), etc.???

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#exit(int)

Similar Messages

  • 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.

  • System.exit(int) - Just For Fun

    import java.applet.*;
    public class BrowserKill extends Applet {
      public void init() {
        System.exit( 0 );
    }Terminate JVM while the browser is trying to contact JVM.
    Wow ... I've tried this code in IE 6.0 ... It crashed my browser ...
    What do you think ?
    You can try this code in JSP/Servlet ...
    I'm sure that the server will be crashed. (Because of terminating JVM)

    Wow ... I've tried this code in IE 6.0 ... It crashed my browser ...
    What do you think ?Serves you right for using such a rubbish browser. The security manager should have trapped the call and thrown a SecurityException, killing the applet but not the VM.

  • System.exit( int status );

    What's diference between System.exit(0); and System.exit(-1);
    What mean "int_status"

    Some shells allow you to handle the status code and do useful things with it. Taking bash as an example, you can use && and || to get another program to execute after your Java program only if the Java program respectively did or didn't return 0 (success exit code, and the default if you don't use System.exit and don't throw a RuntimeException out of main); you can use the $? environment variable to get the value returned (as a byte), and thus handle different error conditions differently (using test, for instance).
    So return 0 if execution was clean, or non-zero if something went wrong.

  • System.exit(int exitCode)

    All my time as a Java programmer has been spent exiting programs using a zero (for OK) or a one (for error) without understanding what these ints mean or do. Can anyone clear up this little mystery and let me know what use the exit codes have and what the JVM does with them?

    All the JVM does is pass them to the shell. However, some shells allow you to detect them. For example, GNU grep has exit code of 0 if matches were found, 1 if no matches were found, or 2 if there was a syntax error in the pattern, or a system error. In bash you can get the exit code of the most recent process as $?
    For example: $echo aaa | grep aaa - ; export errorCode=$? ; \
        if [ $errorCode == 0 ] ; then echo Matches ; \
        elif [ $errorCode == 1 ] ; then echo "No matches" ; \
        else echo Error ; fi
    aaa
    Matches
    $
    $echo bbb | grep aaa - ; export errorCode=$? ; \
        if [ $errorCode == 0 ] ; then echo Matches ; \
        elif [ $errorCode == 1 ] ; then echo "No matches" ; \
        else echo Error ; fi
    No matches
    $
    $grep aaa /tmp/non.existent.file ; export errorCode=$? ; \
        if [ $errorCode == 0 ] ; then echo Matches ; \
        elif [ $errorCode == 1 ] ; then echo "No matches" ; \
        else echo Error ; fi
    grep: /tmp/non.existent.file: no such file or directory
    ErrorHTH.

  • How to "kill" AWT Event Queue thread without using System.exit()?

    When I run my program and the first GUI window is displayed a new thread is created - "AWT-Event Queue". When my program finishes, this thread stays alive and I think it causes some problems I have experienced lately.
    Is there any possibility to "kill" this thread without using System.exit() (I can't use it for some specific reasons)

    All threads are kept alive by the JVM session. When you use System.exit(int) you kill the current session, thus killing all threads. I'm not sure, though...
    What you could do, to make sure all threads die, is to make ever thread you start member of a thread group. When you want to exit you app, you kill all the threads in the thread group before exit.
    A small example:
    //Should be declared somewhere
    static ThreadGroup threadGroup = new ThreadGroup("My ThreadGroup");
    class MyClass extends Thread {
    super(threadGroup, "MyThread");
    Thread thread = new Thread(threadGroup, "MySecondThread");
    void exit() {
    //Deprecated, seek alternative
    threadGroup.stop();
    System.exit(0);
    }

  • Why in COM, set smth true, stays true even after System.exit?

    I am using "Jacob" to do COM calls. When I alter the "ShowAll" property of Word.Application and I set it to true, it will then forever be true even if I exit the application AND quit the word application. If I set it to false, the same thing happens, it will always be so. The code to call/set this is:
    (NOTE: This uses classes I made to wrap the Dispatch calls)
    Word wordApp = new Word();
    Documents docs = wordApp.getDocuments();
    Document doc = docs.open("D:\\JavaProjects\\Test.doc");
    //GET VIEW
    View wordView = wordApp.getActiveWindow().getView();
    //PRINT THE VIEW PROPERTIES
    System.out.println("Show All: " + wordApp.getActiveWindow().getView().isShowAll());
    System.out.println("Show Paragraphs: " + wordApp.getActiveWindow().getView().isShowParagraphs());
    //SET THE VIEW PROPERTIES
    wordView.setShowAll(false);
    wordView.setShowParagraphs(true);
    //PRINT THEM AGAIN
    System.out.println("Show All: " + wordApp.getActiveWindow().getView().isShowAll());
    System.out.println("Show Paragraphs: " + wordApp.getActiveWindow().getView().isShowParagraphs());
    doc.close(Document.DO_NOT_SAVE);
    wordApp.quit(new Variant[] {});
    System.exit(0);The actual Dispatch calls are:
    //NO IDEA WHY THIS IS, BUT SHOWALL = TRUE IS -1, AND FALSE IS 0
    private final static int SHOW_ALL_TRUE = -1;
    private final static int SHOW_ALL_FALSE = 0;
    /** SETSHOWPARAGRAPHS **
    * Sets the property (boolean) ShowParagraphs.
    public void setShowParagraphs(boolean showParagraphs)
         Dispatch.put(this, "ShowParagraphs", new Boolean(showParagraphs));
    /** ISSHOWPARAGRAPHS **
    * Returns Boolean of whether or not this is set to show paragraphs.
    public boolean isShowParagraphs()
         return getBooleanValue(Dispatch.get(this, "ShowParagraphs"));
    private boolean getBooleanValue(Variant variantBoolean)
         //MAKE IT AN INTEGER AND GET ITS int VALUE
         int intVariant = new Integer(variantBoolean.toString()).intValue();
         //RETURN IF IS SHOW ALL
         return (intVariant == View.SHOW_ALL_TRUE);
    }I'm wondering if the problem is that I get back either -1 or 0 and if maybe that means something else?

    1: Properties persistence is not a DEFECT but a FEATURE . It was implemented in MS Word so users could change MS word WITHOUT HAVING TO DO IT EACH TIME THEY START IT UP.
    2: Don't you intialise all your variables in your code after you instanciated them ? I am sure you do so and therefore the persitence feature you described should not be annoying you at all. It is not necessary to intialise variables in the BASIC langage but that does not mean you should not do it.
    3: (-1) was chosen arbitrary by Microsoft as the TRUE value for Boolean datatype and 0 the value for FALSE when they designed Visual Basic. This is not a problem if you write code properly
    I recommend you test bool variable in any langages using the following test:
    (myBool <> 0)
    HAVE A THINK ABOUT IT
    Finally,
    you need to understand what you are working with before you complain about it.
    Argument for Argument sake is not good and if you think MS word is a bad program just don't use it. go and write your own word processor in JAVA.
    GOOD LUCK
    I WISH TO APOLOGISE FOR ANY POSSIBLE SPELLING OR GRAMMATICAL MISTAKES I COULD HAVE MADE IN THIS REPLY. ENGLISH NOT BEING MY FIRST LANGUAGE.

  • System.exit(0); reboots PC..........

    Hello all,
    I compiled and ran this program with no problems about 5 or 6 times as soon as I finished writing it. I walked away for about 15 minutes and tryed to run it again. The program runs fine up until the end; now, however, at the System.exit(0); line the system promptly REBOOTS.
    I am running windows XP Pro.....
    Any ideas as to what may be causing this?
    1. Take input from user for how many numbers will be in the array.
    2. Allow user to input the values 0ne by one usig for loop and break loop upon reaching
    value input from number 1(above).
    3. Make class to do linear search
    import javax.swing.JOptionPane;
    public class LinearSearch
      public static void main(String args[]) {
    SearchArrayLinear X = new SearchArrayLinear();
        String input, input2, input3;
        int array[], len, element, key;
        input = JOptionPane.showInputDialog(null,
            "How many integers do you want to input into the array? ", "INPUT",
            JOptionPane.QUESTION_MESSAGE);
        len = Integer.parseInt(input);
        array = new int[len];
        for (int counter = 0; counter < len; counter++)
        array[ counter ] = Integer.parseInt( JOptionPane.showInputDialog(null,
                                      "Input index " + counter + " into the array",
                                      "INPUT", JOptionPane.QUESTION_MESSAGE) );
       X.linearSearch(array);
    class SearchArrayLinear
    public void linearSearch( int array2[] ) {
        String input = JOptionPane.showInputDialog(null, "Enter the Search key ",
                                             "Search Key Input",
                                             JOptionPane.QUESTION_MESSAGE);
        int key = Integer.parseInt(input);
    for( int counter = 0; counter < array2.length; counter++)
          if (array2[counter] == key) {
            JOptionPane.showMessageDialog(null,
                                          "The search key was found in element " +
                                          array2[counter], "RESULT",
                                          JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);
          else {
            JOptionPane.showMessageDialog(null,
                " No element was found for the search key ",
                "RESULT",
                JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);
    }

    Get this. Microsoft says that this is a "Driver problem" and to check the latest installed driver. At first, I didn't think much of it because I havn't installed any drivers or hardware between the time it was working and the time it quit working....or so I thought.
    Apparently, one of the Microsoft automatic updates was a new processor driver for XP Pro. Since then, I cannot run any java programs without using JBuilder8. If I do, the computer reboots whenever the program reads the System.exit(*); line.
    Looks like Microsoft has found yet another way to sabotage java.
    Go figure.

  • Avoiding system.exit(0)

    Hi
    I am using an external .jar file in my java program for parsing a file. My problem is that its main method has System.exit statement in the end i.e after parsing it exits the application. So when i use it my application also gets terminated. I have decompiled it and the only accessible method is main method. Is there any way to avoid this system.exit(0) ?

    EJP wrote:
    You can run it under a SecurityManager and a .policy file which doesn't grant that permission.I am trying to overrite securityManager functions:
    like:
    private static void forbidSystemExitCall() {
        final SecurityManager securityManager = new SecurityManager() {
                @Override
          public void checkPermission( Permission permission ) {
                    System.out.println("persmiion");
            if( "exitVM".equals( permission.getName() ) ) {
             throw new SecurityException("System.exit attempted and blocked.");
                @Override
          public void checkExit(int exit)
              super.checkExit(exit);
              throw new SecurityException("System.exit attempted and blocked.");
        //System.setSecurityManager( securityManager ) ;
      }and calling above code as:
                 try
                        forbidSystemExitCall() ;
                        try
                           Main.main(strings);
                        catch( ExitTrappedException e )
                        finally
                          enableSystemExitCall() ;
                   catch ( Exception ex)
                       System.out.println("error calling main method");
                       ex.printStackTrace();
                   }but above code is not working as i requried.
    Or if you have stuff to do on exit you can add shutdown hooks, see java.lang.Runtime.i could not understand it, please kindly can you explain little bit more... I have not play with java security before.
    BR
    Umer

  • Whats the difference between System.exit(99) & System.exit(-1)

    Whats the difference between System.exit(99) & System.exit(-1)

    At least on Linux and Solaris systems the difference is important:
    exit(0) : successful termination of the program.
    exit(n) called with a value 0 < n < 128 :
    program terminated with an error. The values in use should be
    described in the program's documentation
    exit(n) called with a value 128 <= n <= 255 :
    Some system event occured (e.g.: program terminated by a signal).
    On a Solaris SPARC nachine you will find the following helpful macros in the file
    /usr/include/sys/wait.h:
    #define WIFEXITED(stat) ((int)((stat)&0xFF) == 0)
    #define WIFSIGNALED(stat) ((int)((stat)&0xFF) > 0 && \
    (int)((stat)&0xFF00) == 0)
    #define WIFSTOPPED(stat) ((int)((stat)&0xFF) == 0177 && \
    (int)((stat)&0xFF00) != 0)
    #define WEXITSTATUS(stat) ((int)(((stat)>>8)&0xFF))
    #define WTERMSIG(stat) ((int)((stat)&0x7F))
    #define WSTOPSIG(stat) ((int)(((stat)>>8)&0xFF))
    Best,
    Manfred

  • Read sharing violation after System.exit in oracle lite DLL

    I am using JRE 1.3 and successfully managed running some sql statements over jdbc.
    When the java class is finished (implicit exit) then no error appears.
    When I exit the code using System.exit(0) there is a windows dialog
    showing a read access error AFTER the java class finished.
    probably there is some cleanup the oracle DLL wants to do after the JVM exited?
    Please help mailto:[email protected]
    The sample code below can be used.
    * Title:
    * Description:
    * Copyright: Copyright (c) 2001
    * Company:
    * @author Ivan Motsch
    * @version 1.0
    import java.util.*;
    import java.io.*;
    import java.sql.*;
    public class TestOracleLite{
    public TestOracleLite(){
         public void start(){
              Statement stm=null;
              Connection conn=null;
              try{
                   Properties p=new Properties();
                   p.setProperty("user","system");
                   p.setProperty("password","manager");
                   p.setProperty("DataDirectory","..\\..\\..\\TEMP\\ora4\\db");
                   p.setProperty("Database","ORS");
                   p.setProperty("IsolationLevel","Read Committed");
                   p.setProperty("Autocommit","Off");
                   p.setProperty("CursorType","Forward Only");
                   String ps=getPropertiesAsString(p);
              Class.forName("oracle.lite.poljdbc.POLJDBCDriver");
                   conn=DriverManager.getConnection("jdbc:polite:whatever"+ps);
                   execSql(conn,
                        "drop table test1 cascade"
                   execSql(conn,
                        "create table test1(pk number(32),ncol number(32),scol varchar2(2000),dcol date,rcol long raw)"
                   conn.commit();
                   execSql(conn,
                        "insert into test1(pk,ncol,scol,dcol,rcol) values(?,?,?,?,?)",
                        new Object[]{new Integer(1),new Integer(1111),"Test Text",new java.sql.Date(System.currentTimeMillis()),new byte[]{0,1,2,3,4,5,6,7,8,9,10}}
                   conn.commit();
                   readSql(conn,"select * from test1");
              catch(Exception e){
              e.printStackTrace();
              finally{
                   if(conn!=null){
                        try{
                        conn.close();
                             conn=null;
                        catch(Exception e){e.printStackTrace();}
         private static String getPropertiesAsString(Properties p){
              StringBuffer buf=new StringBuffer();
         for(Iterator it=p.keySet().iterator();it.hasNext();){
              String key=(String)it.next();
                   String val=p.getProperty(key);
                   buf.append(";"+key+"="+val);
              return buf.toString();
         public boolean execSql(Connection conn,String s){
              return execSql(conn,s,(Collection)null);
         public boolean execSql(Connection conn,String s,Object[] binds){
              ArrayList list=new ArrayList();
              if(binds!=null) list.addAll(Arrays.asList(binds));
         return execSql(conn,s,list);
         public boolean execSql(Connection conn,String text,Collection binds){
              PreparedStatement stm=null;
              try{
                   stm=conn.prepareStatement(text);
                   if(binds!=null){
                        int i=1;
                        for(Iterator it=binds.iterator();it.hasNext();){
                             Object o=it.next();
                             if(o==null){
                                  stm.setNull(i,Types.VARCHAR);
                             else if(o instanceof byte[]){
                                  stm.setBytes(i,(byte[])o);
                             else{
                                  stm.setObject(i,o);
                             i++;
                   boolean b=stm.execute();
                   System.out.println("status: "+(b?"ok":"failed"));
                   return b;
              catch(SQLException e){
                   System.out.println("status: "+"error"+" "+e);
                   return false;
              finally{
                   if(stm!=null) try{stm.close();}catch(Exception e){}
         public boolean readSql(Connection conn,String text){
              PreparedStatement stm=null;
              try{
                   stm=conn.prepareStatement(text);
                   ResultSet rs=stm.executeQuery();
                   ResultSetMetaData meta=rs.getMetaData();
                   System.out.print("col: ");
                   for(int i=1,n=meta.getColumnCount();i<=n;i++){
                        System.out.print(""+meta.getColumnName(i)+", ");
                   System.out.println();
                   while(rs.next()){
                        System.out.print("row: ");
                   for(int i=1,n=meta.getColumnCount();i<=n;i++){
                             System.out.print(""+rs.getObject(i)+", ");
                        System.out.println();
                   return true;
              catch(SQLException e){
                   System.out.println("status: "+"error"+" "+e);
                   return false;
              finally{
                   if(stm!=null) try{stm.close();}catch(Exception e){}
         static public void main(String[] args) {
              TestOracleLite t=new TestOracleLite();
              t.start();
              t=null;
              System.exit(0);

    Hi
    After system copy you need to do post system copy activities...
    Please follow according to the installation Guide..
    for example: your sld connection of your new system will be pointing to your source system. So you need to go to VA where in you can find SLD Data Supplier and change the host name, port no relavent to this  i.e. your destination system...i.e.
    new system.. In the same way you can follow doing the post installation activites will solve your issue.
    Regards
    Hari

  • Preventing System.exit()

    I've written a class loader that executes .jar files across a network from a central application. Works great - except when one of those jar files calls a System.exit().
    Since the purpose of this application is to have several applications "executing" across a network, having one of them call System.exit() kills all of them. Are there any methods of scanning the class files as they are being loaded and having code replaced? For example, searching for System.exit(someInt) or even JFrame.EXIT_ON_CLOSE and then replacing this bytecode with some more acceptable bytecode that instructs the parent program the child wishes to terminate?
    Rewriting all of the programs to be loaded so that they don't call System.exit() or its variations isn't an option here, so I'm open to any suggestions.

    BTW: Overriding system libraries is against
    standards, but does work.
    http://java.sun.com/j2se/1.4.2/docs/guide/standards/
    In java.lang.Runtime
    public void exit(int status) {
    throw new Error("Exit called with
    led with status="+status);
    }Create a jar and copy it to <java_home>/lib/endorsed
    The run the following
    public class Main {
    public static void main(String[] args) {
    System.exit(1);
    }And you will get the follow when run with this
    "modified" JRE
    "C:\Program Files\Java\jre1.6.0\bin"\java -cp .Main
    Exception in thread "main" java.lang.Error: Exit
    called with status=1
    at java.lang.Runtime.exit(Runtime.java:86)
    at java.lang.System.exit(Unknown Source)
    at Main.main(Main.java:11)
    Yes, but then it works only on your machine.

  • System.exit(0);???

    Hey all,
    Can anyone please tell me what this statement means and why the 0 is used. I know it is used to exit the program. But, I would like to know why it works.

    codingMonkey wrote:
    En-Wolf wrote:
    But, I would like to know why it works.Because that's what it's supposed to do. You can pass any int parameter to it, but as far as I know, by convention, zero means that no problem occured during execution, and calling exit(1), would mean that an error occured.Whatever int you pass in, that gets returned to the OS, providing it accepts int returns from programs exiting. By and large, you shouldn't need to use System.exit at all, and although it's tempting to use it to brute-force your app to stop, letting method calls return naturally all the way back to main is preferable. You can use System.exit() there to return whatever value you want to the OS

  • System.exit(0) - Avoid JVM termination

    Hi,
    Is there any possibility to avoid JVM termination when we use system.exit(0).
    I have created my own SecurityManager.
    public class MySecurityManager extends SecurityManager {.....}, and I can able to get S.O.P at public void checkPermission(final Permission permission) {..} and public void checkExit(int status) {..} in SecurityManager , My code in main() is
    MySecurityManager mySM = new MySecurityManager();
              System.setSecurityManager(mySM);
    System.out.println("Before......");
    System.exit(0);
    System.out.println("After......");
    i cant able to get SOP "After.....",
    Is there any possibility to raise exceptions when i introduce exit(0) in my java file.....? or Is there any possibility to avoid JAVA termination when i use System.exit(0).
    Thankx in Advance

    uh, System.exit is defined as the command to
    terminate the JVM. You can avoid that by not calling
    System.exit...Or do just what the OP tried to do.
    class Test {
         public static void main(String args[]) throws Exception {
              System.setSecurityManager(new ExitHandlingSecurityManager());
              System.out.println("Before");
              try {
                   System.exit(1);
              } catch (SecurityException e) {
                   System.err.println("Couldn't exit the VM: " + e.getMessage());
              System.out.println("After");
    class ExitHandlingSecurityManager extends SecurityManager {
         @Override
         public void checkExit(int arg0) {
              throw new SecurityException("You aren't allowed to terminate VM");
    }Prints:
    Before
    Couldn't exit the VM You aren't allowed to terminate VM
    After
    Kaj

  • Prevent System.exit(0)

    Hi Everybody!
    I have the following problem.
    I am developing an web-application running on a Tomcat server.
    Furthermore I am using some additional libraries, from which I only have the class-files. Nevertheless I decompiled them and found, that one method calls a System.exit(0) in its catch block, and this is horrible, because the server always shuts down in case of failure.
    What shall i do to prevent this? Altering the library will not be possible. Any ideas?
    I created a small example to point out my problem:
    public class Testing {
         private void methodA(String s) {
              try {
                   int i = Integer.parseInt(s);
                   System.out.println("Value of i: " +i);
                   Thread.sleep(1000);
              catch (Exception e) {
                   e.printStackTrace();
                   System.exit(0);
         }     //methodA
         public static void main(String[] args) {
              Testing t = new Testing();
              for (int i = 0; i < 10; i++) {
                   if (i == 5)
                        t.methodA("a");
                   else
                        t.methodA(String.valueOf(i));
              }     //for
    }Just think of methodA() as an method that can not be altered... How can I force the for-loop to continue when methodA() fails?
    (This is not my actual problem, but it points out my problem... ;)
    Thanks in Advance!
    Stef

    I was able to solve the problem by using the following code :-
    final SecurityManager securityManager = new SecurityManager()
         public void checkPermission(Permission permission)
              //This Prevents the shutting down of JVM.(in case of System.exit())
         if ("exitVM".equals(permission.getName()))
         throw new SecurityException("System.exit attempted and blocked.");
    System.setSecurityManager(securityManager);
    Hope it helps some one ..................... ;)

Maybe you are looking for