Exceptions

This page summarizes the design of the exception library: the types, the system variables and the predefined constants. The tables list every standard error and warning, with its code and the pattern of its message. The statements that raise and handle exceptions are explained in Processing.
Draft: the codes and the message patterns below are proposed. The forms of raise and the Exception module are not final (PRC-08, PRC-09).

Library Design

The exception module belongs to the standard library: it is imported by default. It is written in Eve. A process that cannot continue raises an error; the workflow jumps into the recover region, where the developer reads $error. A warning does not interrupt the process: it is added to $trace and the process goes on. Warnings are reported in the final exit status of the primary aspect.

Types

TypeMembersRole
exception.Errorcode: Integer, message: String, module: String, line: Integer, job: String, errors: ()ErrorAn error that interrupts a process. The base class of every error class; errors lists the errors of the aspects of a failed parallel group.
exception.Warningcode: Integer, message: String, module: String, line: IntegerA condition that is reported but does not interrupt the process.
exception.Callline: String, method: StringOne entry of the call stack.

The class Error in the module Exception:

** system exception type
module exception is
  export (Error, raise, expect, assert, warn);

  ** an error: its class and its code identify it; the exit code of the process is separate
  class Error = {code: Integer, message: String, module: String, line: Integer, job: String} <: Object is
    constructor(code = 4, message = "" :String) => (@self) is
      let self := Object();
      let self.code := code;
      let self.message := message;
    return;
  end Error;

end exception;

System Variables and Objects

NameTypeMeaning
$errorErrorThe last error of the process.
$stack()CallThe list of calls that led to the error.
$trace()ErrorThe list of errors and warnings of the process.

The other system variables are listed in System Variables.

Signatures

Only the signatures are given. A declaration with the keyword external keeps only the signature: it is implemented in Zig by the virtual machine. The source of the module is evevm/lib/exception.eve. An exception is an object {code: x, message: y}; raise is overloaded and accepts a constructor call, a code constant with a message, a code with a message, an exception object, or only a message (code 4).

** raise an exception object
external raise(e: Error);

** raise an error with a code and a message
external raise(code: Integer, message: String);

** raise an error with the default code 4
external raise(message: String);

** raise $err_expect when the condition is false
external expect(condition: Logic, message := "");

** raise $err_assert when the condition is false
external assert(condition: Logic, message := "");

** report a warning and go on
external warn(code: Integer, message: String);

Predefined Constants

Every standard error and warning has a predefined constant: $err_name for an exception and $wrn_name for a warning. The constant is the integer code. In the recover region you compare it with the code of the error:

recover
  if $error.code == $err_file do
    print "Skip the missing file: " / $error.message;
    resume;
  else
    abort;
  done;

The constants are read only. An error is not an exit code: a primary aspect that ends with an unhandled error ends with the exit code 4, and reports the code and the message of the error (see Exit Codes).

Error Classes

Every standard error is an object of a class derived from Error, and every class has its code (table Standard Exceptions). In the recover region you can test the class with is and read its fields, or compare the code with a constant:

recover
  if $error is IoError do
    retry;                          ** a transient error: try the job again
  else if $error.code == $err_file do
    resume;                         ** a missing file: go on
  else
    abort;
  done;

The recover region is one region: it has no list of classes. Inside it you test the error with if … is as above, or with match: a class as the pattern of a when tests the class of the object, as is does. Every error is an Error, so $error is Error is always true, and a class below another is also the other: SqlError is a DatabaseError.

recover
  match $error
    when FormatError do
      print "bad file: {$error.message}";
    when DatabaseError do
      print "database: {$error.code}";
    when other do
      abort;
  done;

The function error_type(code) gives the class of a code, or null when the language has no class for it, so a program that keeps a code (in a log, in a message from another machine) finds the class again: error_type($err_format) == FormatError.

Raising Errors

An error is made with raise. Besides the text and the pair code and message, raise takes an error object. Error(code, message) makes one with a code of your own, and every other class is made with a message only, its code being the code of the class. Named arguments add fields, which recover reads from $error.

raise "something is wrong";                         ** code 4
raise (17, "the invoice is closed");                ** a standard code, ArgumentError
raise DivideError("the rate can not be 0");         ** code 12
raise Error(code: 20, message: "no disk", detail: "D:");

recover
  print $error.detail;                              ** D:

A program defines its own errors as classes below Error. The class gives its code, from 1000 up, as a member with a value, and it may have fields of its own; a class below such a class keeps the code of its parent. The object has the fields code and message of every error (the message is the argument message:), and recover reads the other fields from $error. $error is Failure tells it from the standard errors. The compiler refuses a class below Error without a code or with a code below 1000, and a number written in raise (code, text) or in Error(code, text) that is not a standard code. The way to end a program with a code of your own is over n;, not an exit code in a class.

class Failure = {code: 1001, detail: String} <: Error;
class DiskFailure = {device: String} <: Failure;

raise Failure(message: "bad", detail: "disk");
raise DiskFailure(message: "full", device: "D:");

expect and assert take a message after the condition, with else or with a comma: expect balance >= 0 else "the balance is negative";. The message is the message of the error.

A warning is reported with warn(code, message): it writes unit:line: warning code: message on the standard error and the process goes on.

Code Ranges

CodesUse
1 to 9The statements of the language: panic 1, expect 2, assert 3, raise 4 by default, then warnings. These are error codes, not exit codes.
10 to 999Reserved for the compiler, the virtual machine and the standard library. The tables below list them; a program does not add to them.
1000 and aboveThe errors defined by a program, as classes below Error. Keep the codes of a program unique.

Standard Exceptions

A message pattern is the message of the error. A name in braces is replaced with the value that caused the error. When a new exception is needed, add it to this table with the next free code of its range, then use its constant.

CodeClassConstantMessage patternRaised by
1Panic$err_panicthe message given to panic, or "Panic in line {line}"panic
2ExpectError$err_expect"Unexpected error in line {line}", or the custom messageexpect
3AssertError$err_assert"Assertion failed in line {line}", or the custom messageassert
4Error$err_raisethe message given to raiseraise without a code
10IndexError$err_index"Index {index} is out of range {first}..{last}"collections, strings
11KeyError$err_key"Key {key} not found"DataMap, DataSet
12DivideError$err_divide"Division by zero"arithmetic
13OverflowError$err_overflow"Overflow in {operation}"arithmetic
14ConvertError$err_convert"Cannot convert {value} to {type}"type conversion
15ParseError$err_parse"Cannot parse {text} as {type}"parse, literals read at run time
16NullError$err_null"null value used as {type}"any use of null
17ArgumentError$err_argument"Invalid argument {name}: {reason}"functions, methods, processes
20FileError$err_file"File not found: {path}"file and folder classes
21AccessError$err_access"Access denied: {path}"file and folder classes
22IoError$err_io"Input/output error on {path}: {reason}"streams, files
30ModuleError$err_module"Module {name} not found in {library}"from … use
31ProcessError$err_process"Aspect {name} not found, or it has no process main"apply, start
40MemoryError$err_memory"Out of memory while allocating {size}"virtual machine
41TimeoutError$err_timeout"Time-out after {time}"channels, parallel groups
42DeadlockError$err_deadlock"Deadlock: every task of the group waits on a channel"parallel groups
43OutputError$err_output"Output {name} is given to two tasks of the group"start
44RecursionError$err_recursion"Recursion limit reached at depth {depth}"virtual machine
45ParallelError$err_parallel"{count} aspects of the group failed"; the list is $error.errorsparallel groups
46ChannelError$err_channel"Channel {name} is closed"channels (level 4)
50DatabaseError$err_database"Database error {sqlstate} on {table}: {reason}"databases (level 5)
51ConnectionError$err_connection"Cannot reach {host}: {reason}"; transientdatabases
52ConstraintError$err_constraint"Constraint {constraint} violated by {key}"databases
53ConflictError$err_conflict"Row {key} was changed by someone else (version {version})"databases, optimistic lock
54MappingError$err_mapping"Mapping of {table} does not match the database: {differences}"; fatal, exit code 4databases, first use of a connection
55CommitError$err_commit"Cannot tell if transaction {transaction} was committed"; fataldatabases, two connections in a job
56FormatError$err_format"Bad {format} at line {line}, column {column}: {reason}"data files (level 5)
57HttpError$err_http"HTTP {status} from {url}"HTTP client
58BatchError$err_batch"{count} records of batch {batch} failed"; the records are in $error.faileddatabases
59SqlError$err_sql"SQL function {name} failed: {reason}"; a DatabaseErrorsql functions

Standard Warnings

The same rule applies: list every new warning in this table.

CodeConstantMessage patternReported by
5$wrn_deprecated"{name} is deprecated, use {other}"library members marked deprecated
6$wrn_truncate"Value {value} truncated to {type}"type conversion
7$wrn_unused"{name} is declared but never used"compiler

Exit Codes

The exit code of a process is a small number. It tells a shell or a scheduler how the process ended; the error itself is in the message.

Exit codeMeaning
0normal end: return, over, or the normal end of the recover region
1panic
2failed expect, not recovered
3failed assert, not recovered
4unhandled error: raise or a run-time error, not recovered
5unexpected stop: Ctrl+C in the interpreter; a halt breakpoint in debug mode that the user ends with Ctrl+C or stop instead of resuming; recursion too deep; out of memory; hard time-out

Read next: Databases