unchecked exceptions are also known as runtime exceptions.
Unchecked exceptions are those which need to be taken care at runtime.
Benefit of using RunTime Exception >
Whenever runtime exception occurs execution of program is interrupted, but by handling these kind of exception we avoid such interruptions and end up giving some meaningful message to user.
Which classes are which exception?
The class RuntimeException and all its subclasses are unchecked exceptions.
The class Error and all its subclasses are unchecked exceptions.
Propagating unchecked exception (NullPointerException) >
unchecked exceptions are automatically propagated in java.
Now, i’ll be explaining you how unchecked exception was propagated.
Let’s see step by step what happened in above program >
- JVM called main method
- step 1 - main called method1()
- step 2 - method1 called method2()
- step 3 - method2 called method3()
- step 4 - method3 automatically propagated exception to method2() [because, unchecked exceptions are propagated automatically]
- step 5 - method2 automatically propagated exception to method1() [because, unchecked exceptions are propagated automatically]
- step 6 - method2 automatically propagated exception to main() [because, unchecked exceptions are propagated automatically]
- main() automatically propagated exception to JVM [because, unchecked exceptions are propagated automatically]
Let's see how stack of methods is formed >
In the above program, stack is formed and an exception is first thrown from the top of the stack [ method3() ] and it remains uncaught there, and starts coming down the stack to previous methods to method2(), then to method1(), than to main() and it remains uncaught throughout.
exception remains uncaught even after reaching bottom of the stack [ main() ] so it is propagated to JVM and ultimately program is terminated by throwing exception [ as shown in output ].
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
EXCEPTIONS - Top 60 interview questions and answers in java for fresher and experienced - detailed explanation with diagrams Set-1 > Q1- Q25