How We Loose Exception Information in Java






We can also throw a different Exception than one we caught.Once we do that we get a similar effect as when using fillInStackTrace().The original information of site of Exception is lost . The information we will have the new Exception from the position we throw the Exception.

I have written here the throw keyword and its functionality in detail.
let us check the code:

public class RethrowNew{

     public static void main(String []args){
        try{
            myMethod();
        }
        catch(Exception e)
        {
          System.out.println("Caught in main"); 
          e.printStackTrace();
          throw new NullPointerException("From main");
        }
     }
        public static void myMethod() throws Exception{
            System.out.println("Originatring from myMethod()");
            throw new Exception("from myMethod()");
        }
    }
 
The output of the code:
$javac RethrowNew.java
$java -Xmx128M -Xms16M RethrowNew
Originatring from myMethod()
Caught in main
java.lang.Exception: from myMethod()
at RethrowNew.myMethod(RethrowNew.java:16)
at RethrowNew.main(RethrowNew.java:5)
Exception in thread "main" java.lang.NullPointerException: From main
at RethrowNew.main(RethrowNew.java:11)
The final Exception only knows that it has come from main() method not from myMethod().Throwable is not necessary in any of the Exception operations.We never have to worry about cleaning up the previous Exceptions or any of the Exception.As they are created by the keyword new,Garbage collector will automatically clean them.
How We Loose Exception Information in Java How We Loose Exception Information in Java Reviewed by Animesh Chatterjee on October 04, 2018 Rating: 5

No comments:

Powered by Blogger.