What are unchecked (RuntimeExceptions) in java




Contents of page >
  • 1) What are unchecked exceptions in java
  • 2) Advantage/Benefit of using unchecked/RunTime Exception in java >
  • 3) Example of  unchecked exceptions in java
  • 4) Which classes are which unchecked exception in java?
  • 5) Propagating unchecked exception (NullPointerException) in java >
  • 6) Let's see how stack of methods is formed >


1) What are unchecked exceptions in java

unchecked exceptions are also known as runtime exceptions.
Unchecked exceptions are those which need to be taken care at runtime.

2) Advantage/Benefit of using unchecked/RunTime Exception in java >
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 in java.

3) Example of  unchecked exceptions in java

Most common and frequently occurring unchecked (runtime) in java.



4) Which classes are which unchecked exception in java?
The class RuntimeException and all its subclasses are unchecked exceptions.
Likewise,
The class Error and all its subclasses are unchecked exceptions.

5) Propagating unchecked exception (NullPointerException) in java >
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]

6) 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 */


RELATED LINKS>


Labels: Core Java
eEdit
Must read for you :