Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

try: practical reference

try: practical reference: try delimits code whose exceptions are handled by catch and whose cleanup runs in finally.

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

Syntax

try /* grammar-specific form */

try delimits code whose exceptions are handled by catch and whose cleanup runs in finally.

Keep it narrow around the operation whose failure you can classify.

An overly broad try lets catch attribute failures from unintended statements to the same cause.

try requires catch or finally; catch filters run before stack unwinding.

The complete program actually uses try; its exact expected stdout is ok.

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("ok"); } catch { Console.WriteLine("error"); }

Result

ok

The complete program actually uses `try`; its exact expected stdout is `ok`.

Sources