10.2 Exceptions (original) (raw)
10.2 Exceptions🔗ℹ
Exceptions in The Racket Guide introduces exceptions.
See Exceptions for information on the Racket exception model. It is based on a proposal by Friedman, Haynes, and Dybvig [Friedman95].
Whenever a primitive error occurs in Racket, an exception is raised. The value that is passed to the current exception handler for a primitive error is always an instance of theexn structure type. Every exn structure value has amessage field that is a string, the primitive error message. The default exception handler recognizes exception values with theexn? predicate and passes the error message to the currenterror display handler (see error-display-handler).
Primitive procedures that accept a procedure argument with a particular required arity (e.g., call-with-input-file,call/cc) check the argument’s arity immediately, raisingexn:fail:contract if the arity is incorrect.
10.2.1 Error Message Conventions🔗ℹ
Racket’s error message convention is to produce error messages with the following shape:
‹srcloc›: ‹name›: ‹message›; ‹continued-message› ... ‹field›: ‹detail› ...
The message starts with an optional source location, ‹srcloc›, which is followed by a colon and space when present. The message continues with an optional ‹name› that usually identifies the complaining function, syntactic form, or other entity, but may also refer to an entity being complained about; the ‹name› is also followed by a colon and space when present.
The ‹message› should be relatively short, and it should be largely independent of specific values that triggered the error. More detailed explanation that requires multiple lines should continue with each line indented by a single space, in which case ‹message›should end in a semi-colon (but the semi-colon should be omitted if‹continued-message› is not present). Message text should be lowercase—using semi-colons to separate sentences if needed, although long explanations may be better deferred to extra fields.
Specific values that triggered the error or other helpful information should appear in separate ‹field› lines, each of which is indented by two spaces. If a ‹detail› is especially long or takes multiple lines, it should start on its own line after the‹field› label, and each of its lines should be indented by three spaces. Field names should be all lowercase.
A ‹field› name should end with ... if the field provides relatively detailed information that might be distracting in common cases but useful in others. For example, when a contract failure is reported for a particular argument of a function, other arguments to the function might be shown in an “other arguments...” field. The intent is that fields whose names end in ...might be hidden by default in an environment such as DrRacket.
Make ‹field› names as short as possible, relying on‹message› or ‹continued message› text to clarify the meaning for a field. For example, prefer “given” to “given turtle” as a field name, where ‹message› is something like “given turtle is too sleepy” to clarify that “given” refers to a turtle.
10.2.2 Raising Exceptions🔗ℹ
Raises an exception, where v represents the exception being raised. The v argument can be anything; it is passed to the current exception handler.
If barrier? is true, then the call to the exception handler is protected by a continuation barrier, so that multiple returns/escapes are impossible. All exceptions raised byracket functions effectively use raise with a#t value for barrier?.
Breaks are disabled from the time the exception is raised until the exception handler obtains control, and the handler itself isparameterize-breaked to disable breaks initially; seeBreaks for more information on breaks.
Examples:
23 > (struct my-exception exn:fail:user ()) #f > (raise 'failed #t) uncaught exception: failed
Raises the exception exn:fail, which contains an error string. The different forms produce the error string in different ways:
- (error message-sym) creates a message string by concatenating"error: " with the string form of message-sym. Use this form sparingly.
- (error message-str v ...) creates a message string by concatenating message-str with string versions of the vs (as produced by the current error value conversion handler; seeerror-value->string-handler). A space is inserted before each v. Use this form sparingly, because it does not conform well to Racket’s error message conventions; considerraise-arguments-error, instead.
- (error who-sym format-str v ...) creates a message string equivalent to the string created by
(format (string-append "~s: " format-str) who-sym v ...)
When possible, use functions such as raise-argument-error, instead, which construct messages that follow Racket’s error message conventions.
In all cases, the constructed message string is passed tomake-exn:fail, and the resulting exception is raised.
Examples:
> (error 'failed) error: failed > (error "failed" 23 'pizza (list 1 2 3)) failed 23 'pizza '(1 2 3) > (error 'method-a "failed because ~a" "no argument supplied") method-a: failed because no argument supplied
Like error, but constructs an exception withmake-exn:fail:user instead of make-exn:fail. The default error display handler does not show a “stack trace” forexn:fail:user exceptions (see Continuation Marks), soraise-user-error should be used for errors that are intended for end users.
Creates an exn:fail:contract value and raises it as an exception. The name argument is used as the source procedure’s name in the error message. The expected argument is used as a description of the expected contract (i.e., as a string, but the string is intended to contain a contract expression).
In the first form, v is the value received by the procedure that does not have the expected type.
In the second form, the bad argument is indicated by an indexbad-pos (counting from 0), and all of the original arguments v are provided (in order). The resulting error message names the bad argument and also lists the other arguments. Ifbad-pos is not less than the number of vs, theexn:fail:contract exception is raised.
The error message generated by raise-argument-error is adjusted via error-contract->adjusted-string and thenerror-message->adjusted-string using the default'racket realm.
Examples:
> (feed-machine 'turkey) feed-machine: contract violation expected: integer? given: 'turkey > (define (feed-cow animal) (unless (eq? animal 'cow) (raise-argument-error 'feed-cow "'cow" animal)) "fed the cow") > (feed-cow 'turkey) feed-cow: contract violation expected: 'cow given: 'turkey > (define (feed-animals cow sheep goose cat) (unless (eq? goose 'goose) (raise-argument-error 'feed-animals "'goose" 2 cow sheep goose cat)) "fed the animals") > (feed-animals 'cow 'sheep 'dog 'cat) feed-animals: contract violation expected: 'goose given: 'dog argument position: 3rd other arguments...: 'cow 'sheep 'cat
Like raise-argument-error, but using the given realmfor error-message adjustments.
Added in version 8.4.0.2 of package base.
Like raise-argument-error, but the error message describe vas a “result” instead of an “argument.”
Like raise-result-error, but using the given realmfor error-message adjustments.
Added in version 8.4.0.2 of package base.
Creates an exn:fail:contract value and raises it as an exception. The name is used as the source procedure’s name in the error message. The message is the error message; if message contains newline characters, each extra line should be suitably indented (with one extra space at the start of each line), but it should not end with a newline character. Each field must have a corresponding v, and the two are rendered on their own line in the error message; each v is formatted using the error value conversion handler (seeerror-value->string-handler), unless v is aunquoted-printing string, in which case the string content isdisplayed without using the error value conversion handler. When a string produced by the error value conversion handler or in an unquoted-printing string contains a newline but does not start with a newline, then the string is started on its own line with extra spaces added before each line to indent the string content.
The error message generated by raise-arguments-error is adjusted via error-message->adjusted-string using the default'racket realm.
Examples:
> (raise-arguments-error 'eat "fish is smaller than its given meal" "fish" 12 "meal" 13) eat: fish is smaller than its given meal fish: 12 meal: 13 > (raise-arguments-error 'eat "not edible" "candidate" (unquoted-printing-string "a banana made\nof wax")) eat: not edible candidate: a banana made of wax
Changed in version 8.15.0.2 of package base: Added indentation for v strings that contain newlines.
Like raise-arguments-error, but using the given realmfor error-message adjustments.
Added in version 8.4.0.2 of package base.
Changed in version 8.15.0.2: Added indentation for v strings that contain newlines.
Creates an exn:fail:contract value and raises it as an exception to report an out-of-range error. The type-descriptionstring describes the value for which the index is meant to select an element, and index-prefix is a prefix for the word “index.” The indexargument is the rejected index. The in-value argument is the value for which the index was meant. The lower-bound and upper-boundarguments specify the valid range of indices, inclusive; if upper-boundis below lower-bound, the value is characterized as “empty.” If alt-lower-boundis not #f, and if index is between alt-lower-boundand upper-bound, then the error is report as index being less than the “starting” index lower-bound.
Since upper-bound is inclusive, a typical value is one less than the size of a collection—for example, (sub1 (vector-length vec)), (sub1 (length lst)), and so on.
The error message generated by raise-range-error is adjusted via error-message->adjusted-string using the default'racket realm.
Examples:
> (raise-range-error 'vector-ref "vector" "starting " 5 #(1 2 3 4) 0 3) vector-ref: starting index is out of range starting index: 5 valid range: [0, 3] vector: '#(1 2 3 4) > (raise-range-error 'vector-ref "vector" "ending " 5 #(1 2 3 4) 0 3) vector-ref: ending index is out of range ending index: 5 valid range: [0, 3] vector: '#(1 2 3 4) > (raise-range-error 'vector-ref "vector" "" 3 #() 0 -1) vector-ref: index is out of range for empty vector index: 3 > (raise-range-error 'vector-ref "vector" "ending " 1 #(1 2 3 4) 2 3 0) vector-ref: ending index is smaller than starting index ending index: 1 starting index: 2 valid range: [0, 3] vector: '#(1 2 3 4)
Like raise-range-error, but using the given realmfor error-message adjustments.
Added in version 8.4.0.2 of package base.
Like raise-argument-error, but with Racket’s old formatting conventions, and where expected is used as a “type” description instead of a contract expression. Use raise-argument-erroror raise-result-error, instead.
The error message generated by raise-type-error is adjusted via error-message->adjusted-string using the default'racket realm.
Similar to raise-arguments-error, but using Racket’s old formatting conventions, with a required v immediately after the first message string, and with further messagestrings that are spliced into the message without line breaks or space. Use raise-arguments-error, instead.
The error message generated by raise-mismatch-error is adjusted via error-message->adjusted-string using the default'racket realm.
Changed in version 8.15.0.2 of package base: Added indentation for v strings that contain newlines.
Creates an exn:fail:contract:arity value and raises it as an exception. The name is used for the source procedure’s name in the error message.
The arity-v value must be a possible result from procedure-arity, except that it does not have to be normalized (see procedure-arity? for the details of normalized arities); raise-arity-errorwill normalize the arity and use the normalized form in the error message. If name is a procedure, its actual arity is ignored.
The arg-v arguments are the actual supplied arguments, which are shown in the error message (using the error value conversion handler; see error-value->string-handler); also, the number of supplied arg-vs is explicitly mentioned in the message.
The error message generated by raise-arity-error is adjusted via error-message->adjusted-string using the default'racket realm.
Example:
> (raise-arity-error 'unite (arity-at-least 13) "Virginia" "Maryland") unite: arity mismatch; the expected number of arguments does not match the given number expected: at least 13 given: 2 arguments...: "Virginia" "Maryland"
Like raise-arity-error, but using the given realmfor error-message adjustments.
Added in version 8.4.0.2 of package base.
The same as raise-arity-error, but using the arity representation described with procedure-arity-mask.
Added in version 7.0.0.11 of package base.
Like raise-arity-mask-error, but using the given realmfor error-message adjustments.
Added in version 8.4.0.2 of package base.
Like raise-arity-error, but reports a “result” mismatch instead of an “argument” mismatch. The name argument can be#f to omit an initial source for the error. Thedetail-str argument, if non-#f, should be a string that starts with a newline, since it is added near the end of the generated error message.
The error message generated by raise-result-arity-error is adjusted via error-message->adjusted-string using the default'racket realm.
Example:
> (raise-result-arity-error 'let-values 2 "\n in: example" 'a 2.0 "three") let-values: result arity mismatch; expected number of values not received expected: 2 received: 3 in: example arguments...: 'a 2.0 "three"
Added in version 6.90.0.26 of package base.
Like raise-result-arity-error, but using the given realmfor error-message adjustments.
Added in version 8.4.0.2 of package base.
Creates an exn:fail:syntax? value and raises it as an exception. Macros use this procedure to report syntax errors.
The name argument is usually #f when expris provided; it is described in more detail below. Themessage is used as the main body of the error message; ifmessage contains newline characters, each new line should be suitably indented (with one space at the start), and it should not end with a newline character.
The optional expr argument is the erroneous source syntax object or S-expression (but the expression #f cannot be represented by itself; it must be wrapped as a syntax object). The optional sub-expr argument is a syntax object or S-expression (again, #f cannot represent itself) withinexpr that more precisely locates the error. Both may appear in the generated error-message text iferror-print-source-location is #t. Source location information in the error-message text is similarly extracted fromsub-expr or expr when at least one is a syntax object and error-print-source-location is #t.
If sub-expr is provided and not #f, it is used (in syntax form) for the exprs field of the generated exception record, else the expr is used if provided and not#f. In either case, the syntax object is consed ontoextra-sources to produce the exprs field, orextra-sources is used directly for exprs if neitherexpr nor sub-expr is provided and not #f. The extra-sources argument is also used directly forexprs in the unusual case that the sub-expr orexpr that would be included in exprs cannot be converted to a syntax object (because it contains a cycle).
The form name used in the generated error message is determined through a combination of the name, expr, andsub-expr arguments:
- When name is #f, and when expr is either an identifier or a syntax pair containing an identifier as its first element, then the form name from the error message is the identifier’s symbol.
- When name is #f and when expr is not an identifier or a syntax pair containing an identifier as its first element, then the form name in the error message is"?".
- When name is a symbol, then the symbol is used as the form name in the generated error message.
The message-suffix string is appended to the end of the error message. If not "", it should normally start with a newline and two spaces to add extra fields to the message (seeError Message Conventions).
If specified, exn should be a constructor or function that has the same signature as the exn:fail:syntax constructor.
Examples:
> (raise-syntax-error #f "bad syntax" '(bad syntax)) ?: bad syntax in: (bad syntax) > (raise-syntax-error #f "unbound identifier" 'unbound-id #:exn exn:fail:syntax:unbound) ?: unbound identifier in: unbound-id
Changed in version 6.90.0.18 of package base: Added the message-suffix optional argument.
Changed in version 8.4.0.6: Added the exn optional argument.
An unquoted-printing string wraps a string andprints, writes, and displays the same way that the string displays. An unquoted-printing stringis especially useful with raise-arguments-error to serve as a field “value” that causes literal text to be printed as the field content.
The unquoted-printing-string? procedure returns #tif v is a unquoted-printing string, #fotherwise. The unquoted-printing-string creates aunquoted-printing string value that encapsulates the strings, and unquoted-printing-string-value returns the string within a unquoted-printing string.
Added in version 6.10.0.2 of package base.
10.2.3 Handling Exceptions🔗ℹ
Installs f as the exception handler for thedynamic extent of the call to thunk. If an exception is raised during the evaluation of thunk (in an extension of the current continuation that does not have its own exception handler), then f is applied to the raised value in the continuation of the raise call (but the continuation is normally extended with a continuation barrier; see Prompts, Delimited Continuations, and Barriers andraise).
Any procedure that takes one argument can be an exception handler. Normally, an exception handler escapes from the context of theraise call via abort-current-continuation or some other escape mechanism. To propagate an exception to the “previous” exception handler—that is, the exception handler associated with the rest of the continuation after the point where the called exception handler was associated with the continuation—an exception handler can simply return a result instead of escaping, in which case the raise call propagates the value to the previous exception handler (still in the dynamic extent of the call to raise, and under the same barrier, if any). If an exception handler returns a result and no previous handler is available, the uncaught-exception handleris used.
A call to an exception handler is parameterize-breaked to disable breaks, and it is wrapped withcall-with-exception-handler to install an exception handler that reports both the original and newly raised exceptions via theerror display handler and then escapes via the error escape handler.
A parameter that determines an uncaught-exception handler used byraise when the relevant continuation has no exception handler installed with call-with-exception-handler orwith-handlers. Unlike exception handlers installed withcall-with-exception-handler, the uncaught-exception handler must not return a value when called by raise; if it returns, an exception is raised (to be handled by an exception handler that reports both the original and newly raised exception).
The default uncaught-exception handler prints an error message using the current error display handler (see error-display-handler), unless the argument to the handler is an instance of exn💔hang-up. If the argument to the handler is an instance of exn💔hang-upor exn💔terminate, the default uncaught-exception handler then calls the exit handler with 1, which normally exits or escapes. For any argument, the default uncaught-exception handler then escapes by calling the current error escape handler (seeerror-escape-handler). The call to each handler isparameterized to set error-display-handler to the default error display handler, and it is parameterize-breaked to disable breaks. The call to the error escape handler is further parameterized to set error-escape-handler to the defaulterror escape handler; if the error escape handler returns, then the default error escape handler is called.
When the current error display handler is the default handler, then the error-display call is parameterized to install an emergency error display handler that logs an error (see log-error) and never fails.
(with-handlers ([pred-expr handler-expr] ...) body ...+)
Evaluates each pred-expr and handler-expr in the order that they are specified, and then evaluates the bodys with a new exception handler during its dynamic extent.
The new exception handler processes an exception only if one of thepred-expr procedures returns a true value when applied to the exception, otherwise the exception handler is invoked from the continuation of the with-handlers expression (by raising the exception again). If an exception is handled by one of thehandler-expr procedures, the result of the entirewith-handlers expression is the return value of the handler.
When an exception is raised during the evaluation of bodys, each predicate procedure pred-expr is applied to the exception value; if a predicate returns a true value, the corresponding handler-expr procedure is invoked with the exception as an argument. The predicates are tried in the order that they are specified.
Before any predicate or handler procedure is invoked, the continuation of the entire with-handlers expression is restored, but alsoparameterize-breaked to disable breaks. Thus, breaks are disabled by default during the predicate and handler procedures (seeBreaks), and the exception handler is the one from the continuation of the with-handlers expression.
The exn:fail? procedure is useful as a handler predicate to catch all error exceptions. Avoid using (lambda (x) #t) as a predicate, because the exn:break exception typically should not be caught (unless it will be re-raised to cooperatively break). Beware, also, of catching and discarding exceptions, because discarding an error message can make debugging unnecessarily difficult; instead of discarding an error message, consider logging it via log-error or a logging form created bydefine-logger.
Examples:
got a syntax error got a syntax error
(with-handlers* ([pred-expr handler-expr] ...) body ...+)
Like with-handlers, but if a handler-expr procedure is called, breaks are not explicitly disabled, and the handler call is in tail position with respect to the with-handlers* form.
10.2.4 Configuring Default Handling🔗ℹ
The error escape handler is normally called directly by an exception handler, in a parameterization that sets the error display handler and error escape handler to the default handlers, and it is normally parameterize-breaked to disable breaks. To escape from a run-time error in a different context, useraise or error.
Due to a continuation barrier around exception-handling calls, an error escape handler cannot invoke a full continuation that was created prior to the exception, but it can abort to a prompt (seecall-with-continuation-prompt) or invoke an escape continuation (see call-with-escape-continuation).
A parameter for the error display handler, which is called by the default exception handler with an error message and the exception value. More generally, the handler’s first argument is a string to print as an error message, and the second is a value representing a raised exception. An error display handler can print errors in different ways, but it should always print to the current error port.
The default error display handler displays its first argument to the current error port (determined by thecurrent-error-port parameter) and extracts a stack trace (seecontinuation-mark-set->context) to display from the second argument if it is an exn value but not anexn:fail:user value.
The default error display handler in DrRacket also uses the second argument to highlight source locations.
To report a run-time error, use raise or procedures likeerror, instead of calling the error display handler directly.
A parameter whose value is used as the maximum number of characters used to print a Racket value that is embedded in a primitive error message.
A parameter whose value is used by the default error display handleras the maximum number of lines of context (or “stack trace”) to print; a single “...” line is printed if more lines are available after the first cnt lines. A 0 value forcnt disables context printing entirely.
A parameter that controls whether read and syntax error messages include source information, such as the source line and column or the expression. This parameter also controls the error message when a module-defined variable is accessed before its definition is executed; the parameter determines whether the message includes a module name. Only the message field of an exn:fail:read,exn:fail:syntax, or exn:fail:contract:variablestructure is affected by the parameter. The default is #t.
A parameter that determines the error value conversion handler, which is used to print a Racket value that is embedded in a primitive error message.
The integer argument to the handler specifies the maximum number of characters that should be used to represent the value in the resulting string. The default error value conversion handler prints the value into a string (using the current global port print handler; see global-port-print-handler). If the printed form is too long, the printed form is truncated and the last three characters of the return string are set to “...”.
When called by function like error, if the string returned by an error value conversion handler is longer than requested, the string is truncated to the requested length. If a byte string is returned instead of a string, it is converted usingbytes->string/utf-8. If any other non-string value is returned, then the string "..." is used. If a primitive error string needs to be generated before the handler has returned, the default error value conversion handler is used.
Calls to an error value conversion handler are parameterized to re-install the default error value conversion handler, and to enable printing of unreadable values (see print-unreadable).
If the string produced by error-value->string-handlercontains a newline but does not start with a newline, then a context that uses the string will add spaces or indentation after each newline as needed. For example, raise-argument-error adds a three-space indentation to the start of each line.
Changed in version 8.15.0.2 of package base: Added indentation convention for string results that contain newlines.
A parameter that determines the error syntax conversion handler, which is used to print a syntax form that is embedded in an error message, such as from raise-syntax-errorwhen error-print-source-location is #t.
The arguments to the handler are analogous to the arguments for aerror value conversion handler as configured witherror-value->string-handler, except that #f can be provided instead of an integer for the length, meaning that the printed form should not be truncated. The first argument is normally asyntax object, but in the same way thatraise-syntax-error accepts other S-expressions, the error syntax conversion handler must also handle representations that are not syntax objects.
Added in version 8.2.0.8 of package base.
A parameter that determines the error syntax name handler, which is used to extract the name of a syntactic form whenraise-syntax-error is called with #f as its first argument and a syntax object as its third argument.
The argument to the handler is a the syntax object provided toraise-syntax-error as its third argument. The result must be a symbol if a name can be extracted from the syntax object,#f otherwise.
Added in version 8.15.0.2 of package base.
Similar to error-value->string-handler, but intended for a module path. The default writes the module path to a string.
Added in version 8.16.0.3 of package base.
10.2.5 Built-in Exception Types🔗ℹ
Exceptions raised by Racket form a hierarchy under exn:
#:extra-constructor-name make-exn:fail #:transparent)
Raised for exceptions that represent errors, as opposed toexn:break.
#:extra-constructor-name make-exn:fail:contract #:transparent)
Raised for errors from the inappropriate run-time use of a function or syntactic form.
#:extra-constructor-name make-exn:fail:contract:arity #:transparent)
Raised when a procedure is applied to the wrong number of arguments.
#:extra-constructor-name make-exn:fail:contract:divide-by-zero #:transparent)
Raised for division by exact zero.
#:extra-constructor-name make-exn:fail:contract:non-fixnum-result #:transparent)
Raised by functions like fx+ when the result would not be a fixnum.
#:extra-constructor-name make-exn:fail:contract:continuation #:transparent)
Raised when a continuation is applied where the jump would cross a continuation barrier.
#:extra-constructor-name make-exn:fail:contract:variable #:transparent) id : symbol?
Raised for a syntax error that is not a read error. Theexprs indicate the relevant source expressions, least-specific to most-specific.
This structure type implements the prop:exn:srclocs property.
#:extra-constructor-name make-exn:fail:syntax:unbound #:transparent)
Raised by #%top or set! for an unbound identifier within a module.
Raised by the default module name resolver or defaultload handler to report a module path—a reported in thepath field—whose implementation file cannot be found.
The default module name resolver raises this exception only when it is given a syntax object as its second argument, and the default load handler raises this exception only when the value of current-module-path-for-load is a syntax object (in which case both the exprs field and the path field are determined by the syntax object).
This structure type implements the prop:exn:missing-module property.
#:extra-constructor-name make-exn:fail:read #:transparent) srclocs : (listof srcloc?)
Raised for a read error. The srclocs indicate the relevant source expressions.
#:extra-constructor-name make-exn:fail:read:eof #:transparent)
Raised for a read error, specifically when the error is due to an unexpected end-of-file.
#:extra-constructor-name make-exn:fail:read:non-char #:transparent)
Raised for a read error, specifically when the error is due to an unexpected non-character (i.e., “special”) element in the input stream.
#:extra-constructor-name make-exn:fail:filesystem #:transparent)
Raised for an error related to the filesystem (such as a file not found).
#:extra-constructor-name make-exn:fail:filesystem:exists #:transparent)
Raised for an error when attempting to create a file that exists already.
#:extra-constructor-name make-exn:fail:filesystem:version #:transparent)
Raised for a version-mismatch error when loading an extension.
Raised for a filesystem error for which a system error code is available. The symbol part of an errno field indicates the category of the error code: 'posix indicates a C/Posixerrno value, 'windows indicates a Windows system error code (under Windows, only), and 'gai indicates agetaddrinfo error code (which shows up only inexn:fail:network:errno exceptions for operations that resolve hostnames, but is allowed in exn:fail:filesystem:errnoinstances for consistency).
Raised by the default module name resolver or defaultload handler to report a module path—a reported in thepath field—whose implementation file cannot be found.
The default module name resolver raises this exception only when it is not given a syntax object as its second argument, and the default load handler raises this exception only when the value of current-module-path-for-load is not a syntax object.
This structure type implements the prop:exn:missing-module property.
#:extra-constructor-name make-exn:fail:network #:transparent)
Raised for TCP and UDP errors.
Raised for a TCP or UDP error for which a system error code is available, where the errno field is as forexn:fail:filesystem:errno.
#:extra-constructor-name make-exn:fail:out-of-memory #:transparent)
Raised for an error due to insufficient memory, in cases where sufficient memory is at least available for raising the exception.
#:extra-constructor-name make-exn:fail:unsupported #:transparent)
Raised for an error due to an unsupported feature on the current platform or configuration.
#:extra-constructor-name make-exn:fail:user #:transparent)
Raised for errors that are intended to be seen by end users. In particular, the default error printer does not show the program context when printing the error message.
Raised asynchronously (when enabled) in response to a break request. The continuation field can be used to resume the interrupted computation in the uncaught-exception handler orcall-with-exception-handler (but not with-handlers because it escapes from the exception context before evaluating any predicates or handlers).
#:extra-constructor-name make-exn💔hang-up #:transparent)
Raised asynchronously for hang-up breaks. The defaultuncaught-exception handler reacts to this exception type by calling the exit handler.
#:extra-constructor-name make-exn💔terminate #:transparent)
Raised asynchronously for termination-request breaks. The defaultuncaught-exception handler reacts to this exception type by calling the exit handler.
A property that identifies structure types that provide a list ofsrcloc values. The property is normally attached to structure types used to represent exception information.
The property value must be a procedure that accepts a single value—the structure type instance from which to extract source locations—and returns a list of srclocs. Some error display handlers use only the first returned location.
As an example,
Returns #t if v has the prop:exn:srclocsproperty, #f otherwise.
Returns the srcloc-getting procedure associated with v.
A source location is most frequently represented by asrcloc structure. More generally, a source location has the same information as a srcloc structure, but potentially represented or accessed differently. For example, source-location information is accessed from a syntax object with functions like syntax-source and syntax-line, whiledatum->syntax accepts a source location as a list, vector, or another syntax object. For ports, a combination ofobject-name and port-next-location provides location information, especially in a port for which counting has been enabled through port-count-lines!.
The fields of a srcloc instance are as follows:
- source — An arbitrary value identifying the source, often a path (see Paths).
- line — The line number (counts from 1) or#f (unknown).
- column — The column number (counts from 0) or#f (unknown).
- position — The starting position (counts from 1) or#f (unknown).
- span — The number of covered positions (counts from 0) or #f (unknown).
See Printing Compiled Code for information about the treatment ofsrcloc values that are embedded in compiled code.
Formats srcloc as a string suitable for error reporting. A path source in srcloc is shown relative to the value ofcurrent-directory-for-user. The result is #f ifsrcloc does not contain enough information to format a string.
A property that identifies structure types that provide a module path for a load that fails because a module is not found.
The property value must be a procedure that accepts a single value—the structure type instance from which to extract source locations—and returns a module path.
Returns #t if v has the prop:exn:missing-moduleproperty, #f otherwise.
Returns the module path-getting procedure associated with v.
10.2.6 Additional Exception Functions🔗ℹ
The bindings documented in this section are provided by the racket/exn library, not racket/base or racket.
Added in version 6.3 of package base.
Formats exn as a string. If exn is an exn?, collects and returns the output from the current(error-display-handler); otherwise, simply convertsexn to a string using (format "~s\n" exn).
10.2.7 Realms and Error Message Adjusters🔗ℹ
A realm identifies a convention for naming functions and specifying contracts for function arguments and results. Realms are intended to help improve layering and interoperability among languages that are implemented on top of Racket.
Realms primarily enable a language to recognize and rewrite error messages that are generated by lower layers of an implementation. For example, a language’s implementation of “arrays” might use Racket vectors directly, but when an object-type or primitive bounds check fails for a vector, the generated error message mentions “vector” and possibly a contract like vector? and a function name likevector-ref. Since these error messages are identified as being from the 'racket/primitive realm, a language implementation can look for 'racket/primitive to detect and rewrite error messages with minimal danger of mangling error messages from other parts of an application (possibly implemented in the new language) that happen to use the word “vector.”
Each procedure and each module also has a realm. A procedure’s realm is relevant, for example, when it is applied to the wrong number of arguments; in that case, the arity-error message itself is from the'racket/primitive realm, but the error message also should include the name of the procedure, which can be from some different realm. Along similar lines, continuation-mark-set->contextcan report the realm associated with (the procedure for) each frame in a continuation, which might be useful to identify boundary crossings.
The construction of an error message must cooperate explicitly with error-message adjusting. The most basic may to cooperate is through functions like error-message->adjusted-string anderror-contract->adjusted-string, which run error-message adjusters via the current-error-message-adjuster parameter and other adjusters associated with the current continuation usingerror-message-adjuster-key as a continuation-mark key. Functions like raise-argument-error andraise-arity-error use error-message->adjusted-stringand error-contract->adjusted-string with the default realm,'racket. Functions like raise-argument-error* andraise-arity-error* accept an explicit realm argument.
Not all error functions automatically cooperate with error-message adjusting. For example, the raise-reader-error andraise-syntax-error functions do not call adjusters, because they report errors that are intimately tied to syntax (and, along those lines, errors of a more static nature).
Combines name (if it is not #f) with ": "and then message to generate an error-message string, but first giving error-message adjusters a chance to adjust nameand/or message.
Any adjuster functions associated with the current continuation as acontinuation mark with error-message-adjuster-key are run first; the adjusters are run in order from shallowest to deepest. Then, the adjuster value of current-error-message-adjuster is used.
Each adjuster is tried with the 'message protocol, first. If the adjuster responds with #f for 'message, then the'name protocol is tried. Seecurrent-error-message-adjuster for information on the protocols. An adjuster that responds with #f for both is skipped, as is any value associated as continuation mark usingerror-message-adjuster-key where the value is not a procedure that accepts one argument. In addition, the 'name protocol is skipped if the (possibly adjusted) name is #f.
Added in version 8.4.0.2 of package base.
Analogous to error-message->adjusted-string, but for just the contract part of an error message. The result string is typically incorporated into a larger error message that may then be adjusted further.
Adjustment of contract string uses the 'contract protocol as described for current-error-message-adjuster.
Added in version 8.4.0.2 of package base.
A parameter that determines an error-message adjuster that is applied after any adjusters associated to the current continuation viaerror-message-adjuster-key.
An adjuster procedure receives a symbol identifying a protocol, and it must return either #f or a procedure for performing adjustments through that protocol. The following protocols are currently defined, but more may be added in the future:
- 'name: the procedure receives two arguments, a name symbol and a realm symbol; it returns an adjusted name symbol and an adjusted realm symbol.
- 'message: the procedure receives four arguments: a name symbol or #f (which means that no name will be prefixed on the message), a name-realm symbol, an message string, and a message-realm symbol; it returns four adjusted values.
- 'contract: the procedure receives two arguments, a contract string and a realm symbol; it returns an adjusted contract string and an adjusted realm symbol.
A new library or language can introduce additional mode symbols, too. To avoid conflicts, prefix the mode symbol with a collection or library name followed by /.
If an adjuster procedure returns #f for a protocol, it’s the same as returning a function that performs no adjustment and returns its arguments. The default value of this parameter returns #ffor any symbol argument except the protocols listed above, for which it returns a procedure that checks its arguments and returns them with no adjustment.
Added in version 8.4.0.2 of package base.
An uninterned symbol intended for use as a continuation mark key with an error-adjuster procedure value. An error adjuster associated with the key should follow the same protocol as a value ofcurrent-error-message-adjuster.
See error-message->adjusted-string for a description of how marks using this key are can adjust error messages.
Added in version 8.4.0.2 of package base.