Title here
Summary here
Our program demonstrates the concept of error handling and program termination in Lisp. Here’s the full source code:
(defun main ()
;; We'll use error throughout this site to check for
;; unexpected errors. This is the only program on the
;; site designed to raise an error.
(error "a problem")
;; A common use of error is to abort if a function
;; returns an error value that we don't know how to
;; (or want to) handle. Here's an example of
;; raising an error if we get an unexpected error when creating a new file.
(handler-case
(with-open-file (stream "/tmp/file" :direction :output :if-exists :error)
(format stream "Hello, World!"))
(file-error (condition)
(error condition))))
(main)
Running this program will cause it to raise an error, print an error message and backtrace, and exit with a non-zero status.
When the first error in main
is raised, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first error.
$ sbcl --script error.lisp
This is SBCL 2.1.5, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.
SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses. See the CREDITS and COPYING files in the
distribution for more information.
debugger invoked on a SIMPLE-ERROR in thread
#<THREAD "main thread" RUNNING {1002A51263}>:
a problem
Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.
restarts (invokable by number or by possibly-abbreviated name):
0: [ABORT] Exit debugger, returning to top level.
(MAIN)
0] 0
This is SBCL 2.1.5, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.
SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses. See the CREDITS and COPYING files in the
distribution for more information.
; execution aborted
Note that in Lisp, we use the condition system for handling many errors. It’s idiomatic to use handler-case
and error
for error handling and signaling respectively.