Skip to content

Error Handling

Throwing Exceptions

Use throw to raise an exception:

float Divide(float a, float b)
{
if (b == 0.0)
{
throw Exception("Division by zero");
}
return a / b;
}

try / catch / finally

Catch exceptions with a try block:

try
{
float result = Divide(10.0, 0.0);
Console.WriteLine($"{result}");
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
finally
{
Console.WriteLine("Done.");
}

The finally block always runs, whether or not an exception was thrown.

Bare Catch

A bare catch; swallows any exception silently:

try
{
RiskyOperation();
}
catch;

Or with a recovery block:

try
{
RiskyOperation();
}
catch
{
Console.WriteLine("Something went wrong");
}

Catching Specific Types

Catch blocks match exception types from most specific to least specific:

type NetworkError { int code; }
type TimeoutError { int elapsed; }
try
{
FetchData();
}
catch (NetworkError e)
{
Console.WriteLine("Network error");
}
catch (TimeoutError e)
{
Console.WriteLine("Timed out");
}
catch;

Re-throwing

Re-throw the current exception with a bare throw;:

try
{
RiskyOperation();
}
catch (Exception e)
{
LogError(e);
throw;
}

Exception Properties

Message

The Message property returns the exception’s error message:

catch (Exception e)
{
Console.WriteLine(e.Message);
}

StackTrace

The StackTrace property returns the call stack as an iterable collection of StackFrame objects:

catch (Exception e)
{
for (StackFrame frame : e.StackTrace)
{
Console.WriteLine((string)frame);
}
}

Each StackFrame has three fields:

FieldTypeDescription
FunctionNamestringThe function name
FileNamestringThe source file name
LineNumberintThe line number

StackFrame has a string conversion operator that returns a formatted string like "at DoWork() in main.ce:42".

Built-in Exception Types

TypeDescription
ExceptionBase type — all exceptions inherit Message and StackTrace
NullReferenceExceptionNull pointer dereference
StackOverflowExceptionStack overflow from infinite recursion
DivideByZeroExceptionInteger division or modulo by zero
OverflowExceptionArithmetic overflow in checked blocks
IndexOutOfRangeExceptionArray index out of bounds
FFIExceptionUnresolved FFI symbol called at runtime
OutOfMemoryExceptionGC heap memory limit exceeded
ExecutionTimeoutExceptionSandbox execution timeout expired

Runtime trap exceptions (NullReferenceException, DivideByZeroException, OverflowException, IndexOutOfRangeException) are raised automatically by the compiler’s safety checks — no explicit throw is needed. They are catchable via try/catch like any user-thrown exception.

Checked / Unchecked Arithmetic

The checked and unchecked keywords control overflow detection for integer arithmetic.

// Checked: overflow throws OverflowException
checked
{
int x = 2147483647 + 1; // throws OverflowException
}
// Unchecked: overflow wraps silently (default behavior)
unchecked
{
int x = 2147483647 + 1; // wraps to negative, no exception
}

Both support single-statement form:

checked int y = a * b;
unchecked int z = a * b;

Nesting is supported — the inner context overrides the outer:

checked
{
int safe = a + b; // overflow-checked
unchecked
{
int fast = c + d; // wraps silently
}
}

Inside checked blocks, integer +, -, and * use overflow-checked instructions. If the operation overflows, an OverflowException is thrown.

Division by Zero Protection

Integer division (/) and modulo (%) always check for a zero divisor, regardless of checked/unchecked context:

int x = 10 / 0; // throws DivideByZeroException
int y = 10 % 0; // throws DivideByZeroException

See Also

  • FFI — Foreign Function Interface for calling native code
  • Assertions — assert and const assert for invariant checking