2

Consider the following:

(defun my-divide-by-0()
  (condition-case nil
      (/ 1 0)
    (error (progn (message "Could not evaluate: 1/0") nil))))

(defun my-test()
  (interactive)
  (my-divide-by-0)
  (message "Continued"))

When I do M-x my-test, the message Continued appears. How do I modify the error handling in my-divide-by-0 so only the message Could not evaluate: 1/0 would appear and the execution of my program would stop without the necessity to check error conditions in my-test? I tried throwing, but then the message Arithmetic error appears...

3

You didn't raise an error with your error message. You just used message.

So your message actually appeared (check buffer *Messages*), but then execution continued and the second message was displayed.

If you want to stop execution when the error occurs then you need to raise another error. E.g.:

(defun my-divide-by-0 ()
  (condition-case nil
      (/ 1 0)
    (error (error "Could not evaluate: 1/0"))))

And if you want to see the original error message as part of your error message then you need to use a variable in place of nil:

(condition-case err-var...), not (condition-case nil...).

And then raise an error with a message that combines whatever message you want with the original message:

(defun my-divide-by-0 ()
  (condition-case err-var
      (/ 1 0)
    (arith-error (error "Could not evaluate: 1/0, %s" (error-message-string err-var)))))

C-h f condition-case tells you:

When a handler handles an error, control returns to the condition-case and it executes the handler's BODY... with VAR bound to (ERROR-SYMBOL . SIGNAL-DATA) from the error. (If VAR is nil, the handler can't access that information.)

Then the value of the last BODY form is returned from the condition-case expression.

  • I do not see how this answers my question. How does using ERR-VAL help me quit the command on error? – AlwaysLearning Aug 5 '17 at 18:18
  • You're right. I've edited the answer. Hopefully it is more helpful now. – Drew Aug 5 '17 at 18:44
  • Although I still do not get what happens when I raise an error twice, it does what I need! – AlwaysLearning Aug 5 '17 at 18:53
  • 1
    The error is raised by division by zero. But you have a handler that intercepts it, prevent it from being raised to the user. Your handler then raises a different error (which presumably is not handled), showing the message you prefer. – Drew Aug 5 '17 at 21:21
  • 1
    The symbol error has two uses here. Function error raises an error. Inside condition-case, the symbol error is not the function error; it just introduces a (general) error handler. In this context, error is "condition name error which takes in all kinds of errors". See the Elisp manual, node Error Symbols. – Drew Aug 6 '17 at 5:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.