All About RuntimeException in Java



The specialty of Runtime Exception is that it unchecked in nature.So it is not necessary to check for null on every handle that is passed into a method.(We do not know or we do not want to know if the caller of the method has provided a valid handle). In java, part of the standard runtime checking that (java performs internally) if any call is made to a null handle,java automatically throw a NullPointerException. So we never need to write an Exception specification saying that a method may throw a NullPointerException.
As the compiler does not enforce exception specification for RuntimeException,Runtime Exceptions could propagate all the way to main() method without being caught.As a result printStackTrace() is called for that exception as the program exits.It is only possible not to catch an exception like this for RuntimeExceptions since all other handling is carefully enforced by the compiler. Runtime Exception represents either a programming error that we can not catch or one that we , as a programmer should have checked in our code.It means Runtime Exceptions represent a programming error. However this helps in debugging a different way.

public class DoNoCatch{
    static void foo()
    {
        throw new RuntimeException("generating in foo");
    }
    static void goo()
    {
        foo();
    }
     public static void main(String []args){
        goo();
     }
}
 
output of the code:
$javac DoNoCatch.java
$java -Xmx128M -Xms16M DoNoCatch
Exception in thread "main" java.lang.RuntimeException: generating in foo
at DoNoCatch.foo(DoNoCatch.java:4)
at DoNoCatch.goo(DoNoCatch.java:8)
at DoNoCatch.main(DoNoCatch.java:11)
All About RuntimeException in Java All About RuntimeException in Java Reviewed by Animesh Chatterjee on November 20, 2018 Rating: 5

No comments:

Powered by Blogger.