Introduction to Exception - rahul00773/JavaConcepts GitHub Wiki

An unwanted unexpected event that disturbs the normal flow of the program is called an exception.

Example:

  • TyrePunchered exception
  • Sleeping Exception
  • File not found exception etc

It is highly recommended to handle exceptions and the main objective of exception handling is graceful termination of the program.

Exception handling does not mean repairing an exception. We have to provide an alternative way to continue the rest of the program normally. Is the concept of exception handling.

Example: Our program requirement is to read data from a remote file locating in London. At runtime, if the London file is not available. Our program should not be terminated abnormally. We have to provide some local files to continue the rest of the program normally. This way of defining alternative is nothing but exception handling.

try{

"Read data from remote file locating at London"

} catch(FileNotFoundException e){

"Use local file and continue rest of the program normally"

}

Runtime Stack Mechanism

For every thread, JVM will create a runtime stack. Each and every method call performed by that thread will be stored in the corresponding stack. Each entry in the stack is called a stack frame or activation record. After completing every method call the corresponding entry from the stack will be removed.

After completing all method calls the stack will become empty. And the empty stack will be destroyed by JVM just before terminating the thread.

package src.exceptionHandling;

public class Test { public static void main(String[] args){ doStuff(); }

    public static void doStuff(){
    
    doMoreStuff();
    }
    
    public static void doMoreStuff(){
    
    System.out.println("Hello");
}

}