Search code examples
elispemacs24

Try-catch and print trace in elisp


How can this javascript code sample for throw/catch error written using elisp?

throw new Error("Boom!!!")
catch(error){
    console.log(err.stack)
}

Solution

  • Emacs Lisp distinguishes between conditions, a high-level object-oriented construct, and non-local exits, a low-level construct that allows exiting a scope prematurely.

    Conditions are captured using condition-case:

    (condition-case nil
        (error "Error!")
      (error (message "Caught error")))
    

    Non-local exists are handled using catch:

    (progn
      (catch 'catcher
        (throw 'catcher 42))
      (message "Caught .. or perhaps not"))
    

    In general, you should use conditions if you wish to participate in Emacs' error handling protocols, and catch/throw if you only need to exit prematurely.

    In order to compute a backtrace, you may use the function backtrace:

    (catch 'catcher
      (throw 'catcher
        (with-temp-buffer
          (backtrace)
          (buffer-string))))