Skip to content

EN CSharp Exceptions

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

Exceptions, try/catch/finally and throw

Manual C# · Examples UO

try limits the protected region, catch handles a suitable exception, finally cleans up on exit. Filter when selects a handler. throw; rethrows the current exception, preserving the original stack; throw exception; changes its beginning.

Simple example (Example.cs)

Save this example separately as Example.cs. Run it independently of the other examples on this page.

Example.cs:

// PROJECT-EXAMPLE
try { int.Parse("not a number"); }
catch (System.FormatException) { System.Console.WriteLine("Invalid"); }

Result:

Invalid
try
{
    int value = int.Parse("not a number");
    UO.Print(value.ToString());
}
catch (FormatException error)
{
    UO.Print(error.Message);
}
finally
{
    // Dispose resources owned by this scope.
}
int RequirePositive(int value)
{
    if (value <= 0) throw new ArgumentOutOfRangeException(nameof(value));
    return value;
}
UO.Print(RequirePositive(3).ToString());

Don't intercept cancellation without the intention of ending the script. Cleaning should free up its own resources; a canceled game call to finally may throw an exception again. The compilation error is detected before execution and is not a normal error within try the executing code.

Official documentation: Exceptions, try/catch/finally and throw - Microsoft Learn.

Clone this wiki locally