Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

catch: practical reference

catch: practical reference: catch captures an exception of a compatible type after a failed try.

Version: C# language and .NET 10 reference runtime

Syntax

catch /* grammar-specific form */

catch captures an exception of a compatible type after a failed try.

Catch only where you can recover, add context, or translate the error.

An overly broad catch hides defects; throw preserves the stack, while throw ex resets it.

A when filter runs before entering catch and should not itself throw.

The complete program actually uses catch; its exact expected stdout is caught.

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 { throw new InvalidOperationException(); } catch (InvalidOperationException) { Console.WriteLine("caught"); }

Result

caught

The complete program actually uses `catch`; its exact expected stdout is `caught`.

Sources