# 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))

Statistician

1. You can even use the ignore-errors’ macro, which is the same thing, but simpler. :)

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

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


Am I not using it correctly?

3. 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)))

4. jpkotta says:

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))

5. @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) :)