Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

finally: practical reference

finally: practical reference: finally performs cleanup after normal exit or an exception from try.

Version: C# language; verified against C# 14 reference

Syntax

finally /* grammar-specific form */

finally performs cleanup after normal exit or an exception from try.

Use it for deterministic release when using is not sufficient.

An exception thrown by finally can hide the original exception.

It may not run after abrupt process termination; return in try still passes through finally.

The complete program actually uses finally; its exact expected stdout is try\nfinally.

Examples

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

try { Console.WriteLine("try"); } finally { Console.WriteLine("finally"); }

Result

try
finally

The complete program actually uses `finally`; its exact expected stdout is `try\nfinally`.

Sources