Exception:-
Run time stack mechanism:-
An unwanted event that (unexpected) disturbs the normal flow of the program is called an Exception.
Example: FileNotFoundException, SleepingException, BombblastException.
- It is always a good programming practice to handle exceptions.
- The objective of the exception handling is for graceful termination of the program.
- Exception handling does not mean, repairing an exception. We are defining alternative way to continue rest of code normally. This is called Exception handling.
- For every thread JVM creates one runtime stack, all the method calls which are performed by that thread will be stored into the corresponding stack. Each record (entry) in the stack is called activation record or stack frame.
- If a method completed normally then the entry from the stack will be removed. After completing the entire method calls stack is empty, just before terminating the thread JVM destroys the corresponding stack.
class Test { public static void main(String[] args){ doStaff(); } public static void doStaff(){ doStaffMore(); } public static void doStaffMore(){ System.out.println("Hello"); } }
Default Exception Handling:-
- If an exception is raised, the method in which occurs is responsible for creation of an exception object by including the following information
- After creating exception object the method handovers that exception object to JVM.
- JVM checks, is there any exception handling code is available or not.
- If it is not available JVM terminates that method abnormally and corresponding entry from the stack will be removed.
- Then JVM checks for exception handling code in the caller method, if the caller method also doesn’t contain exception handling code then JVM terminates that caller method abnormally and the corresponding entry from the stack will be removed.
- This process will be continued until main method and if the main method also does not contain exception handling code JVM terminates main method abnormally and the corresponding entry from the stack will be removed.
- Just before terminating the program abnormally JVM handovers the responsibility of exception handling to the default exception handler which is the component of JVM.
- Default Exception Handler prints that exception information in the console as follows.
- Name of the Exception
- Description of exception
- Location of Exception (Stack trace)
Exception
in thread “main” java.lang.ArithmeticException:
/ by zero.
At Test.doStaffMore (Test.java
13)
At Test.doStaff
(Test.java)
At Test.main()