How to stop a program in Java

5 Answers

0 votes
class Main {
    public static void main(String[] args) {
        System.out.println("abc");
        
        throw new RuntimeException();
        
        // System.out.println("xyz"); // error: unreachable statement
    }
}


/*
run:

abc
ERROR!
Exception in thread "main" java.lang.RuntimeException
	at Main.main(Main.java:5)

*/

 



answered May 19, 2025 by avibootz
0 votes
class Main {
    public static void main(String[] args) {
        System.out.println("abc");
        
        System.exit(0); // Terminate the program with exit code 0 (normal termination)
        
        System.out.println("xyz"); 
    }
}


/*
run:

abc

*/

 



answered May 19, 2025 by avibootz
0 votes
class Main {
    public static void main(String[] args) {
        System.out.println("abc");
        
        return; // Terminate the program gracefully by returning from the main method
        
        // System.out.println("xyz"); // error: unreachable statement
    }
}


/*
run:

abc

*/

 



answered May 19, 2025 by avibootz
0 votes
class Main {
    public static void main(String[] args) {
        System.out.println("abc");
         
        Runtime.getRuntime().halt(0); // Force terminate the JVM
         
        System.out.println("xyz"); 
    }
}
 
 
/*
run:
 
abc
 
*/

 



answered May 19, 2025 by avibootz
0 votes
class Main {
    public static void main(String[] args) {
        System.out.println("abc");
         
        throw new Error();
         
        // System.out.println("xyz");  // error: unreachable statement
    }
}
 
 
/*
run:
 
ERROR!
abc
Exception in thread "main" java.lang.Error
	at Main.main(Main.java:5)
 
*/

 



answered May 19, 2025 by avibootz

Related questions

1 answer 159 views
159 views asked May 19, 2025 by avibootz
1 answer 149 views
149 views asked May 19, 2025 by avibootz
1 answer 220 views
220 views asked May 19, 2025 by avibootz
1 answer 150 views
150 views asked May 19, 2025 by avibootz
1 answer 147 views
147 views asked May 19, 2025 by avibootz
2 answers 140 views
140 views asked May 19, 2025 by avibootz
1 answer 158 views
158 views asked May 19, 2025 by avibootz
...