Friday, March 15, 2019

Java System exit() Method

Java System exit() Method

The exit() method of System class terminates the current Java virtual machine running on system. This method takes status code as an argument.
  • Note: Status - exit(0) - indicates Successful termination
  • Status - exit(-1) - indicates unsuccessful termination with Exception
  • Status - exit(1) - indicates Unsuccessful termination

Syntax

  1. public static void exit(int status)  

Parameter

status - It is the exit status.

Returns

This method does not return any value.

Exception

If security manager exist and his checkexit method doesn't approve exit with specified status then a SecurityException is thorwn.

Example 1

  1. import java.lang.*;  
  2. public class SystemExitExample1 {  
  3.   
  4.     public static void main(String[] args) {  
  5.         int a[]= {9,8,7,6,5,4,3,2,1};  
  6.         for(int i=0;i<a.length;i++)  
  7.         {  
  8.             if(a[i]>5)  
  9.             {  
  10.             System.out.println("array["+i+"]="+a[i]);  
  11.             }  
  12.             else  
  13.             {  
  14.                 System.out.println("terminating jvm,exiting");  
  15.                 System.exit(0);//Treminatejvm  
  16.             }  
  17.         }  
  18.     }  
  19. }  
Test it Now
Output:
array[0]=9
array[1]=8
array[2]=7
array[3]=6
terminatingjvm,exiting

Example 2

  1. public class SystemExitExample2 {  
  2.   
  3.     public static void main(String[] args) {  
  4.         System.out.println("program will terminate when i is 1");  
  5. for(int i=10;i>0;i--)    {         
  6. System.out.println("your no is "+i);  
  7. if(i==1){  
  8. System.out.println("Value is 1 now terminating your program");  
  9. System.exit(1); //exit program  
  10.             }  
  11.             }  
  12.     }  
  13. }  
Test it Now
Output:
program will terminate when i is 1
your no is 10
your no is 9
your no is 8
your no is 7
your no is 6
your no is 5
your no is 4
your no is 3
your no is 2
your no is 1
Value is 1 now terminating your program

3 streams System.in, System.out, and System.err

Java IO: System.in, System.out, and System.error

The 3 streams System.inSystem.out, and System.err are also common sources or destinations of data. Most commonly used is probably System.out for writing output to the console from console programs.

These 3 streams are initialized by the Java runtime when a JVM starts up, so you don't have to instantiate any streams yourself (although you can exchange them at runtime).

Simple System.out + System.err Example:

Here is a simple example that uses System.out and System.err:
try {
  InputStream input = new FileInputStream("c:\\data\\...");
  System.out.println("File opened...");

} catch (IOException e){
  System.err.println("File opening failed:");
  e.printStackTrace();
}

Exchanging System Streams

Even if the 3 System streams are static members of the java.lang.System class, and are pre-instantiated at JVM startup, you can change what streams to use for each of them. Just set a new InputStream for System.in or a new OutputStream for System.out or System.err, and all further data will be read / written to the new stream.
To set a new System stream, use one of th emethods System.setIn()System.setOut() or System.setErr(). Here is a simple example:
OutputStream output = new FileOutputStream("c:\\data\\system.out.txt");
PrintStream printOut = new PrintStream(output);

System.setOut(printOut);
Now all data written to System.out should be redirected into the file "c:\\data\\system.out.txt". Keep in mind though, that you should make sure to flush System.out and close the file before the JVM shuts down, to be sure that all data written to System.out is actually flushed to the file.

printStackTrace Examples

Java Throwable printStackTrace() method
The printStackTrace() method of Java Throwble class is used to print the Throwable along with other details like classname and line number where the exception occurred.

Syntax


  1. public void printStackTrace()  

Example 1


  1. import java.lang.Throwable;  
  2. public class ThrowablePrintStackTraceExample1 {  
  3.     public static void main(String[] args) throws Throwable {  
  4.    try{  
  5.        int i=4/0;  
  6.    }catch(Throwable e){  
  7.        e.printStackTrace();  
  8.        System.err.println("Cause : "+e.getCause());  
  9.    }  
  10. }  
  11. }  
Output:

java.lang.ArithmeticException: / by zero
 at ThrowablePrintStackTrace.main(ThrowablePrintStackTrace.java:5)
Cause : null


Example 2

  1. public class ThrowablePrintStackTraceExample2 {  
  2.     public static void main(String[] args)throws Throwable {  
  3.         try{  
  4.             exceptionTest();  
  5.         }catch(Throwable t){  
  6.             t.printStackTrace();  
  7.         }  
  8. }  
  9.     public static void exceptionTest() throws Exception{  
  10.         System.out.println("Inside exceptionTest() method");  
  11.         throw new Exception("Throwing localized message!");  
  12.     }  
  13. }  

Output:
Inside exceptionTest() method
java.lang.Exception: Throwing localized message!
 at ThrowablePrintStackTraceExample2.exceptionTest(ThrowablePrintStackTraceExample2.java:11)
 at ThrowablePrintStackTraceExample2.main(ThrowablePrintStackTraceExample2.java:4)

Access Modifiers

ClassExceptions

ClassNotFoundException:

ClassNotFoundException is a runtime exception that is thrown when an application 
triesto load a class at runtime using the: 
Class.forName() or loadClass() or findSystemClass() methods ,
and the class with specified name are not found in the classpath.

For example, the below program will throw ClassNotFoundException 
if the mentioned class “oracle.jdbc.driver.OracleDriver” is not found 
in the classpath.
public class MainClass

{

main

    {

        try

        {

Class

ClassNotFoundException

        {

e

        }

    }

}



o/p:-
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDrive

NoClassDefFoundError:
NoClassDefFoundError is an error that is thrown when the Java Runtime System tries to load the definition of a class, and that class definition is no longer available. The required class definition was present at compile time, but it was missing at runtime.


class A

{

  // some code

}


public class B

{

main

    {

A

    }



}



When you compile the above program, two .class files will be generated. 

One is A.class and another one is B.class

If you remove the A.class file and run the B.class file, Java Runtime System will throw NoClassDefFoundError like below:

o/p:-
Exception in thread "main" java.lang.NoClassDefFoundError: A
at MainClass.main(MainClass.java:10)
Caused by: java.lang.ClassNotFoundException: A


printStackTrace():-
It's a method on Exception instances that prints the stack trace of the instance to System.err.
It's a very simple, but very useful tool for diagnosing an exceptions. It tells you what happened and where in the code this happened.
Here's an example of how it might be used in practice:

try {
    // ...
} catch (SomeException e) { 
    e.printStackTrace();
}