Esta página aún no está traducida al español. Leer la versión en inglés

Exceptions

Errors in Antril - exception classes, throw and rethrow, try, catch and finally, the exceptions of the standard library, uncaught exceptions, and the faults that stop a program instead.

Última actualización: 4 min de lectura Editar en GitHub

En esta página

An error is reported by throwing an exception: an object of a class derived from System.Exception. The innermost try with a matching catch handles it; if none does, the program ends.

Exception classes

System.Exception has a Message and two constructors, new() and new(str message). A program declares its own exceptions with the exception declaration, which adds the Exception suffix and the base class for you (see Declarations):

Antril
public exception NotFound
{
	public:
		str Key;
		new(str key) : base("no " + key) { Key = key; }
}

throw new NotFoundException("port");

A class can also derive from Exception, or from another exception class, directly.

throw

Form What it does
throw value; Throws the object. Its type is a class derived from Exception.
throw; Inside a catch, throws the exception being handled again, unchanged. Elsewhere it is AN2006.

A generic function can throw a value of a type parameter constrained with T : exception.

Warning

Not yet available: throwing a value that is not an object, such as throw 5; (AN2007).

try, catch and finally

AntrilRun
import System;

Check(i32 x) : str
{
	try
	{
		if (x > 0)
			return "positive";
		throw new ArgumentError("not positive");
	}
	catch (ArgumentError e)
	{
		return "caught: " + e.Message;
	}
	finally
	{
		Console.WriteLine("finally for " + x);
	}
}

Main()
{
	Console.WriteLine(Check(1));
	Console.WriteLine(Check(0));

	try
	{
		Int32.Parse("x1");
	}
	catch (FormatError e)
	{
		Console.WriteLine(e.GetType().Name + ": " + e.Message);
	}
}
Terminal
larva run
finally for 1
positive
finally for 0
caught: not positive
FormatError: not a number: x1
  • A try needs at least one catch or a finally (AN0018).
  • catch (T e) handles exceptions of the class T and of classes derived from it, and names the exception e inside its block. The name can be left out: catch (KeyNotFoundError). T is an object type (AN2017).
  • catch with no parentheses handles any exception.
  • The catch clauses are tried in order; the first that matches runs. Put the more specific classes first.
  • finally runs when the try (and its catch) ends, however it ends: normally, by an exception, or by return, break or continue.
  • An exception thrown inside a catch or finally goes to the enclosing try.
  • yield and await cannot go inside a catch (AN2113, AN2116).

An exception thrown inside an async function is kept in its task, and await, Wait() and Result throw it again (see Iterators and async).

Exceptions of the standard library

Exception Thrown when
ArgumentError, ArgumentOutOfRangeError An argument is not one the method takes.
IndexError An index is outside a collection, such as List<T>.
KeyNotFoundError A dictionary does not have the key.
InvalidOperationError The object's state does not allow the operation, such as Dequeue on an empty queue.
OverflowError A checked operation overflows.
FormatError Text cannot be parsed, as in Int32.Parse("x").
IOError, EndOfStreamError A file, folder or stream operation fails (System.IO).
InvalidCastError, MissingMemberError, NotSupportedError A reflection operation cannot be done (System.Reflection).

Uncaught exceptions

An exception that no catch handles ends the program with exit code 1:

Terminal
larva run
before
larva: unhandled exception (type id 461533486)

Faults that are not exceptions

Some errors stop the program at once, without an exception that code could catch. Larva prints a larva panic: line and the program ends with exit code 101:

Fault Message
An array index out of range larva panic: index 3 out of bounds for length 1
An integer division by zero larva panic: division by zero
A switch expression no arm matches, a failed downcast (Dog)animal, or Value of an empty nullable larva panic: null reference

Collections of the library check their arguments and throw exceptions instead: List<T> throws IndexError for an index out of range.

¿Te resultó útil esta página?

No se guarda ninguna dirección; tu nombre de usuario sí, si iniciaste sesión.

Esc