Read the syntax
Wrap failures with useful context and preserve the original exception when rethrowing.
The original FormatException is retained in InnerException.
What it is and why to use it
A lower-level parser might fail while a higher-level import needs to explain which operation failed. An exception constructor accepting an inner exception can retain that cause while adding context. In contrast, a bare throw inside a catch rethrows the current exception without replacing its identity or resetting its stack trace at that catch.
How it works
Pass the caught exception as the innerException constructor argument when translating an error into a different abstraction. Read InnerException only after checking for null. Use throw; to rethrow the current exception; throw error; restarts its stack-trace location at the rethrow statement. Diagnostic traces and messages can expose sensitive information and should not become raw public responses.
Common mistakes and limitations
Do not add layers of identical wrapper messages or discard the underlying cause. Do not catch broad failures merely to return apparent success. Redact and control diagnostic logging, and return a stable user-facing message at the external boundary.
Run the examples locally
These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.
Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.
C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.
Create and enter a project
dotnet new console -n CSharpExample --framework net10.0
cd CSharpExampleCSharpExample.csproj settings used for these examples
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>12.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>Build and run after saving one example in Program.cs
dotnet build
dotnet run --no-buildContinue learning
Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.
Syntax
throw new InvalidOperationException("Import failed", cause);Examples
Retain a parser failure as the cause
Inspect a fixed local exception chain without printing a full stack trace.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
try {
try { throw new FormatException("Expected a score"); }
catch (FormatException cause) { throw new InvalidOperationException("Import failed", cause); }
} catch (InvalidOperationException error) {
Console.WriteLine(error.Message);
Console.WriteLine(error.InnerException?.GetType().Name);
}
- The inner failure is wrapped with the operation-level Import failed message.
- The original FormatException is retained in InnerException.
- The demonstration prints only a controlled summary and the cause’s type. Real production diagnostics need their own privacy and logging policy.
- Expected output: Import failed FormatException
- Translate errors at meaningful abstraction boundaries.
Rethrow the same exception instance
Use a bare rethrow rather than creating an unrelated replacement.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
var original = new InvalidOperationException("Demonstration failure");
try {
try { throw original; }
catch (InvalidOperationException) { throw; }
} catch (InvalidOperationException caught) {
Console.WriteLine(ReferenceEquals(original, caught));
}
- The inner catch does not recover, so it rethrows with throw;.
- The outer handler receives the same exception object, confirmed by ReferenceEquals.
- Bare rethrow also preserves the existing stack information; the example avoids matching unstable machine-specific stack text.
- Expected output: True
- Translate errors at meaningful abstraction boundaries.
Best practices
- Translate errors at meaningful abstraction boundaries.
- Use bare throw for a rethrow and keep sensitive details out of public output.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference