-1

The following program

public class Test {

    public static void main(String[] args) {

        try
        {
            String t = null;
            t.toString();

        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Prints in console:

java.lang.NullPointerException at Test.main(Test.java:9)

And the following program

public class Test {

    public static void main(String[] args) {

        String t = null;
        t.toString();
    }

}

Prints in console:

Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:7)

What is the difference between these two console prints?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • probably you didnt add the class imports here? also there is no difference, you try to edit a null object you are doomed anyhow. if you are asking specifically why the lines are different that are throwing the null then its different on the try catch block ofcourse as you catch the exception and then throw it whereas on the second when it occurs it throws it. – Sir. Hedgehog Oct 04 '18 at 13:44
  • [This](https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors) could help you. – LuCio Oct 04 '18 at 13:53
  • 1
    Possible duplicate of [What is a stack trace, and how can I use it to debug my application errors?](https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors) – yash Oct 04 '18 at 14:54
  • One crashes the program, the other doesn't – Zoe Oct 04 '18 at 16:26
  • Neither is the actual output: both will include a stacktrace. – Mark Rotteveel Oct 04 '18 at 19:45

2 Answers2

0

To know the difference, firstly we have to understand on 'what happens if exception is not handled in JAVA'.

You can refer https://www.javamex.com/tutorials/exceptions/exceptions_uncaught_handler.shtml to understand it.

Based on above reference , we can tell there is no major difference here as the second part of your question will also calls for stack trace, But Thread name will be suffixed to it.

0

The difference between the two, is that in the first example, you caught the exception and printed the exception stack trace. After printing, your program will continue normally (in this case: exit).

In the second example you don't catch the exception, the currently running thread (the main thread) ends abruptly (which in your code also ends the program), and the uncaught exception handler of the thread prints the exception prefixed with the text 'Exception in thread "main" '.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197