-1

So I have created a program which involves the use of exceptions. This seems to be working fine apart from I am getting unwanted error pointers within the output of my code. Here is the output of my code:

************Herbivore caught Exception example************
java.lang.Exception: Herbivores only eat plants!
Exception caught
************Herbivore non-caught Exception example************
Herbivores eat Vegetables
    at QuestionEditor.Rabbit.eat(Rabbit.java:38)
    at QuestionEditor.Main.main(Main.java:25)

I don't want the last two lines of the output within my code because that is just telling me why I am getting an exception but I just want to print out the exception message without these additional error message pointers if that's possible? I'm using NetBeans so I'm not sure if this occurs with every exception program o if I have done someting wrong? I didn't think it was necessary to show the code of my program because there is't actually any errors and it is outputting what I want it to be outputting apart form these additional messages, if you think it's important that I include the code please leave a comment saying so and I will edit it in my question. The preferred output would be:

************Herbivore caught Exception example************
java.lang.Exception: Herbivores only eat plants!
Exception caught
************Herbivore non-caught Exception example************
Herbivores eat Vegetables

If anybody could help that would be appreciated, thanks.

James
  • 25
  • 5
  • Please include the smallest example code that demonstrates this problem. – Jason Nov 24 '16 at 21:52
  • this is caused by `e.printStackTrace()` you could change that line to `System.err.println(e);` but the Stacktrace is a valuable information for finding bugs, you should not suppress it. If you do you should use a logging framework to write the stacktrace to a (log-) file. – Timothy Truckle Nov 24 '16 at 21:53
  • Ah thank you very much, it was because of what you described. – James Nov 24 '16 at 21:55
  • You probably made a duplicate: http://stackoverflow.com/questions/11434431/exception-without-stack-trace-in-java – Fernando Nov 24 '16 at 21:56
  • Define 'error pointer'. – user207421 Nov 24 '16 at 23:57
  • `at QuestionEditor.Main.main(Main.java:25)` would be an example. – James Nov 25 '16 at 00:31

1 Answers1

0

You can achieve this with Thread.UncaughtExceptionHandler. This allows you add code which executes when an exception goes uncaught on a given thread. Within the exception handler, you could just print out the error message. The code for it:

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

    @Override
    public void uncaughtException(Thread t, Throwable e) {
       System.out.println(e.getMessage());
    }
});
Luke Melaia
  • 1,470
  • 14
  • 22