Search code examples
javacrasherlangactor

How to implement Erlang's "Let it crash" concept in java


I have been searching for any simple example on ths concept / design pattern / what ever it is called, i want to see any simple example in java, i want to know if it is possible to apply this concept in an android application or not, i'm already using actor model in android but i want to apply the "Let it crash" pattern to it, where can i find any java examples or explanations for it ... I always see high level discussions with no code in it or even UMLs

I tried nothing since i cant imagine how it is done !


Solution

  • I had a way of doing this for several years (2003-2009) in Java. Then I found out how Erlang works and has been coding Erlang since then. If I have to code Java ever again I will use this pattern for sure.

    The way I did it in Java for some major website projects was this:

    1. Avoid try-catch blocks when you can. Let the code crash on NullPointerExceptions and similar subclasses of RuntimeExceptions.
    2. All Exceptions that inherit from RuntimeException are "OK" and will produce crashes in runtime. Just make sure they are logged (on a server) or handled somehow (in a client). Do this default crash handling at one central place to avoid code duplication.
    3. Sometimes you are forced by the Java compiler to handle a catched Exception. Then just rethrow the catched Exception inside a RuntimeException.

    Here is a classic example of catching the checked exception java.sql.SQLException that the compiler forces you to handle and retrowing is as a RuntimeException.

    try {
      your code here...
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }

    This works like a charm. The complete stacktrace is kept and no information is lost. The compiler is happy and you are happy since you have transformed a Java checked exception into a RuntimeException.

    1. All Exceptions you define yourself and all Exceptions you throw in your code explicitly should inherit from java.lang.RuntimeException.

    Good luck!

    This error handling approach made my Java codebase so much smaller and it did become "Let it crash". Not perfect, but a lot better.