1

I have this idea, that anytime an unhandled exception occurs in my JavaFX program, that instead of relying on console output, I can display an alert to the user. I am thinking that perhaps I can capture the output from System.err to use. Here is what I have tried thus far.

    PrintStream myStream = new PrintStream(System.err) {
        @Override
        public void println(String s) {
            super.println(s);
            Log.debugLog(s); //this function logs to a file and displays an alert to user
        }
    };
    System.setErr(myStream);

This code segment works if I replace System.err with System.out, and System.setErr to System.setOut. However that is capturing System.out, not System.err. I suppose the better question would be, what exact function does System.err call when displaying an error to the console? So that may override it. Any tips are appreciated.

  • Wrap the method call in `try-catch` and its done – XtremeBaumer Feb 08 '19 at 12:52
  • 1
    What makes you think it doesn't work ? Try to call `System.err.println("foobar")` after your change to the `err` stream . – Arnaud Feb 08 '19 at 13:13
  • 1
    Related, maybe even a duplicate: https://stackoverflow.com/questions/13841884/redirecting-system-out-to-a-textarea-in-javafx (You can extend `FilterOutputStream` to keep the output in `System.err`.) However this way you cannot be sure the error is completely printed at a given time. The exact sequence of calls is an implementation detail you shouldn't rely on. – fabian Feb 08 '19 at 13:30
  • Your code will achieve your needs when you call :`System.err.println("foobar")` not `System.out.println("foobar")`. – Menai Ala Eddine - Aladdin Feb 08 '19 at 13:41

2 Answers2

0

I think you have the wrong approach. If you want to display an alert to the user when there is an unhandled Exception, you can do that by setting a DefaultUncaughtExceptionHandler:

Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
       // show alert to user
       e.printStackTrace();
       // do whatever you want with the Exception e

    });
Fabian
  • 136
  • 1
  • 7
  • Awesome, this is exactly what I am looking for. Now, if I wanted to get the contents that e.printStackTrace() would output, what method do I call on e? Specifically, I will want to know what line of code failed. I have tried e.getMessage(), e.fillInStackTrace().toString(), I can't seem to figure it out. – Jacob Jones Feb 09 '19 at 04:09
  • Read here on how to get the line number: https://stackoverflow.com/questions/23903831/how-can-i-get-the-line-number-where-the-exception-was-thrown-using-thread-uncaug Please mark my answer as correct if it solved your problem. – Fabian Feb 13 '19 at 16:40
0

You can create a JavaFX Alert customized to show an exception stack trace along with a brief message. This link shows the code for the below.

enter image description here

Dustin
  • 693
  • 8
  • 20