Skip to main content

How to Catch a Specific Exception Type in C#

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

When something goes wrong in .NET, the code throws an exception, and the program stops unless something catches it. A catch clause that names one exception type handles the failure you expected and lets every other error through, so real bugs still surface.

Syntax​

Syntax
try
{
<code that may throw>
}
catch (<ExceptionType> <ex>)
{
<handle it, for example with <ex>.Message>
}
PartWhat it does
try { ... }Runs the code that may throw.
catch (<ExceptionType> <ex>)Runs only for that exception type or a type derived from it.
<ex>.MessageThe exception's description.

Microsoft's exception-handling statements reference: "When an exception occurs, the runtime checks catch clauses in the specified order, from top to bottom. At most, only one catch block runs for any thrown exception."

The Example​

The example turns the text forty-two into a number with int.Parse, which fails with a FormatException; the catch clause prints the reason.

Prerequisites​

  • The .NET 10 SDK or newer, which runs a single .cs file with dotnet run. This guide uses .NET SDK 10.0.404.

Step 1: Write the Code​

Create a file named main.cs in an empty folder:

main.cs, which calls int.Parse("forty-two") inside try and, in catch (FormatException ex), prints Not a number: with ex.Message.

main.cs
try
{
var number = int.Parse("forty-two");
Console.WriteLine(number);
}
catch (FormatException ex)
{
Console.WriteLine($"Not a number: {ex.Message}");
}

Step 2: Run It​

Terminal
dotnet run main.cs
Output
Not a number: The input string 'forty-two' was not in a correct format.

A zsh terminal where dotnet run main.cs prints Not a number: The input string 'forty-two' was not in a correct format.

int.Parse threw, the rest of the try block was skipped, and the catch clause printed the message. The command is the same in zsh, bash and PowerShell.

Catching a Base Type​

Exception types form a hierarchy: FormatException derives from SystemException, which derives from Exception. A catch (Exception) clause therefore catches a FormatException too, along with almost everything else. Use the specific type when only that failure is expected, and a base type when a whole family of failures should be handled the same way.

When you need both, put the specific clause first. The runtime checks clauses from top to bottom, and the compiler refuses a specific clause that can never be reached.

Common Mistakes​

MistakeWhat happensDo this instead
Putting catch (Exception) above catch (FormatException)error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('Exception')Put specific types first
Catching Exception around a lot of codeReal bugs are handled as if they were the expected failureCatch the specific type, around as little code as possible
An empty catch blockThe failure disappears silentlyAt least log ex.Message

Troubleshooting​

SymptomLikely causeFix
The program still crashes with Unhandled exception.The exception isn't the type you catchRead the type on the Unhandled exception. line and catch that
CS0160 on a catch lineA broader clause sits above itReorder the clauses

FAQ​

Can I leave out the variable name?​

Yes: catch (FormatException) catches the type when you don't need the exception object.

Is there a way to avoid the exception here?​

For parsing, yes: int.TryParse returns false instead of throwing. Exceptions are for failures you can't easily check in advance.

Conclusion​

catch (SomeException ex) handles one kind of failure and gives you its Message; everything else keeps propagating. List specific types before general ones.

Additional Resources​