Thursday, July 9, 2009

Error handling in emacslisp

This is a quick overview of how emacs lisp handles errors in your lisp program. When we place the cursor at the end of a lisp program and press C-x C-e the programs are directly evaluated by the lisp interpreter and there is no intermediate compilation phase. Hence, any error in the code must be handled by the interpreter and that is exactly how it is done.
Code :
(+ 2 "hello")
When you evaluate the above code, it will give you an error in a new buffer as given below. To get out of the error press q.
---------- Buffer: *Backtrace* ---------- :
       Debugger entered--Lisp error:
              (wrong-type-argument number-or-marker-p hello)
       +(2 hello)
       eval((+ 2 (quote hello)))
       eval-last-sexp-1(nil)
       eval-last-sexp(nil)
       call-interactively(eval-last-sexp)

When you evaluate the code (+ 2 "hello") you get the error as given in the Buffer : *Backtrace*. The reason for the error is pretty obvious as the string "hello" is a string and not a number. Thus you see the error (wrong-type-argument number-or-marker-p hello) which basically means that hello is neither a number nor a marker. In this way, emacs lisp provides you with valuable information that helps in detecting and rectifying the error.
Another type of error:
Code :
(this is not a function)

Code :
    Debugger entered--Lisp error: (void-function this)
      (this is not a function)
      eval((this is not a function))
      eval-last-sexp-1(nil)
      eval-last-sexp(nil)
      call-interactively(eval-last-sexp)

The buffer is called backtrace because it shows the complete list of function calls starting with the one that actually caused the error. In this case the problem is that the word "this" does not refer to a valid function definition and hence the interpreter says (void-function this). Before that, it tried eval ((this is not a function)) and so on ... leading to the first function that was called namely call-interactively(eval-last-sexp).

0 comments:

Post a Comment