How do i make a crash handler?

Possible to make a crash handler that displays error logs?

Hi @Aryszin,

One solution is to wrap the entire draw() function content with a try / catch block:

void drawMayRaiseErrors() {
  if (frameCount % 2 == 0) {
    int a = 5 / 0;
  } else {
    assert 0 == 1;
  }
}

void draw() {
  try {
    drawMayRaiseErrors();
  } catch (Exception exc) {
    println("Exception: " + exc);
  } catch (Error err) {
    println("Error: " + err);
  }
}
Exception: java.lang.ArithmeticException: / by zero
Error: java.lang.AssertionError
...

Note that it catches both exceptions and errors since they do not inherit from the same base class.

Also note that it only catches errors in the draw() function and not exceptions thrown in a library or the Processing code itself.

There are different types of error

  1. Syntax errors
  • in Java these prevent the sketch being executed and are picked up in the IDE
  • in Javascript they are only detected when executing the code containing the error and generally cause the program to crash.
  1. Logic errors
  • the program executes but does not work as expected (these can be bastards to debug because there are no error messages)
  1. Runtime errors
  • these are caused by the unexpected e.g. division by zero, opening a non-existent file, array out of bounds … almost always they cause the program to crash
  • in most cases these errors throw exceptions which can be caught using try - catch statements. If they are not caught by the program they get caught by the system which stops the program and depending on your IDE prints a stack trace indicating the type and cause of the exception.

If you want to log these exceptions then you need to catch them, but then if you can catch them you can prevent the program crashing in the first place. :grin:

3 Likes