Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have program recognize it crashed last time?

What is the best way to have a (Java) program recognize it crashed last time it ran and show a message along the lines of "it looks like this program crashed on you last time. Report this problem here: [email protected] ...."

Is there a recommended way of doing this? (Bad?) ideas I had would be:

  • Have the program store a temporary key file at startup and then delete it when closing regularly. If the file exists at startup, show the message.
  • Recognize deadlocks and store an "error file" in this case. If an "error file" exists at startup, show the error message and move the file into an archive or something similar.
like image 731
Epaga Avatar asked Nov 17 '09 13:11

Epaga


1 Answers

There are three reasons why a Java program can crash:

  • Unhandled RuntimeException. This is easy to solve with a try-catch in main.
  • Unhandled Errors. These are rare but can be caught in main also. I usually catch Throwable in main. See below for a template.
  • If you use threads, then look at Thread.setDefaultUncaughtExceptionHandler().
  • Bugs in the VM, or program killed by the user, or hardware violent shutdown. These will lead to a crash which can't be caught. Here, your best option is to create a flag file somewhere with new File(...).deleteOnExit(). Java will clean it up for you if it gets a chance.

The problem with deadlocks is how to detect that you have a deadlock. I haven't seen a consistent way to do that, yet.

import org.apache.commons.lang.exception.ExceptionUtils;

public class Demo
{
    public static void main (String[] args)
    {
        try
        {
            Demo obj = new Demo ();
            obj.run (args);
            System.out.println ("Done.");
        }
        catch (Throwable t)
        {
            ExceptionUtils.printRootCauseStackTrace (t);
        }
    }
}
like image 129
Aaron Digulla Avatar answered Sep 28 '22 06:09

Aaron Digulla