Ignore errors when executing a command in emacs with condition-case

Suppose you want to execute a command in your emacs init file, but this command sometimes return an error. For example, you ask emacs to open a file for you, but the file doesn’t exist. When an error occurs, the rest of the init will not be loaded. Once can make use of the condition-case command to ignore the error. The following is an example:

 <pre class="example">(condition-case nil

(wg-load “~/.emacs.d/workgroups-save”) ;; ignore errors from this command (error nil))

About Vinh Nguyen



  1. @Julien I did try the ignore-errors function, but it didn’t work for me. I tried:

    (wg-load "~/.emacs.d/workgroups-save") ;; ignore errors from this command

    Am I not using it correctly?

  2. You’re using it correctly. It works fine in Emacs 24, I can’t check in Emacs 23 since I don’t have it here, but it should work too. C-h f should show you that the definition is the same as what you did:

    (defmacro ignore-errors (&rest body) `(condition-case nil (progn ,@body) (error nil)))

  3. In a similar vein, I wrap a lot of code that needs a specific library to be loaded in this:

    (defmacro with-library (feature &rest body) “Evaluate BODY only if FEATURE is provided. (require FEATURE) will be attempted.” (declare (indent defun)) `(when (require ,feature nil ‘noerror) ,@body))

    Then if some library doesn’t exist, it won’t break my set up (it just won’t have that functionality). As you can see, inside is a non-error-raising invocation of require.

    (with-library ‘foo (global-set-key (kbd “C-c f”) ‘foo-do-something) (global-set-key (kbd “C-c f”) ‘foo-do-something-else))

  4. @jpkotta: You won’t raise an error if you bind a key in a not bound function. Just pressing the key binding will raise an error, so you do not need to require the file. Letting the autoload do the job is even better.

    If you set variables or such things that require the file to be loaded, you want to use `eval-after-load’, which is more optimal, since it will set the settings as soon as the lib is loaded (via autoload, for example) :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>