Skip to main content

How to Catch Every Exception with a catch Clause Without a Type in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

A catch clause with no type in parentheses, just catch, catches every exception the try block throws. Put it last, after the clauses for the exceptions you expect, so it gets only what they don't.

The reference on exception-handling statements: A catch clause without any specified exception type matches any exception and, if present, must be the last catch clause. The C# language specification gives it a name: A catch clause that specifies neither an exception type nor an exception variable name is called a general catch clause. A try statement can only have one general catch clause, and, if one is present, it shall be the last catch clause.

With no variable, it can't read the exception. The specification again: Unless a catch clause includes an exception variable name, it is impossible to access the exception object in the filter and catch block. So use it when what went wrong doesn't change what you do.

Syntax​

Syntax
try
{
<code that can throw>
}
catch (<ExceptionType>)
{
<code for an exception you expect>
}
catch
{
<code for every other exception>
}
PartWhat it is
catch (<ExceptionType>)Optional: a clause for an exception you expect, such as FormatException. Clauses like this come first
catchThe general catch clause: no type and no variable. It catches every exception that the clauses above it don't, and it must be the last clause
<code for every other exception>Runs for any other exception. It can't read the exception, because there's no variable

The Example​

A console app called CatchEverything adds up how many items are in four boxes, from counts typed by hand: 4, four, 12 and 99999999999. A FormatException clause skips the text that isn't a number, and a general catch clause skips anything else that goes wrong.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n CatchEverything
cd CatchEverything
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/CatchEverything/CatchEverything.csproj:
Determining projects to restore...
Restored /Users/you/source/CatchEverything/CatchEverything.csproj (in 41 ms).
Restore succeeded.

dotnet new console -n CatchEverything creates a folder named CatchEverything with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or CatchEverything.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the counts and the try block:

Program.cs (the counts and the try block)
// How many items are in each box, typed by hand.
string[] counts = ["4", "four", "12", "99999999999"];
int total = 0;

foreach (string text in counts)
{
try
{
total += int.Parse(text);
Console.WriteLine($"'{text}': counted");
}

int.Parse(text) turns the text into an int, and total += adds it to the total. Both are in the try block, so a count that can't be read is never added.

Then the clause for the exception you expect:

Program.cs (a clause with a type)
// A catch clause with a type handles exceptions of that type.
catch (FormatException)
{
Console.WriteLine($"'{text}': not a number, skipped");
}

int.Parse throws a FormatException when the text isn't a number, so four ends up here.

Last, the general catch clause and the total:

Program.cs (the general catch clause)
// A catch clause without a type handles every other exception. It must come last.
catch
{
Console.WriteLine($"'{text}': could not be counted, skipped");
}
}

Console.WriteLine($"Total: {total}");

catch with nothing after it catches any exception that the clause above it didn't. 99999999999 is a number, but too big for an int, so int.Parse throws an OverflowException (the FAQ shows it), and it ends up here.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
'4': counted
'four': not a number, skipped
'12': counted
'99999999999': could not be counted, skipped
Total: 16

macOS-style terminal window titled Terminal — CatchEverything showing dotnet run printing '4': counted, then 'four': not a number, skipped, then '12': counted, then '99999999999': could not be counted, skipped, and Total: 16

4 and 12 were counted, for a total of 16. The text four isn't a number, and the FormatException clause skipped it as not a number. 99999999999 threw another type of exception, so the general catch clause skipped it as could not be counted. After each one, the loop went on to the next count.

The Complete File​

macOS-style code window titled Program.cs — CatchEverything showing an array of four typed counts, a foreach with a try block that adds each parsed count to a total, a catch clause for FormatException, a general catch clause without a type, and the total printed at the end

Program.cs
// How many items are in each box, typed by hand.
string[] counts = ["4", "four", "12", "99999999999"];
int total = 0;

foreach (string text in counts)
{
try
{
total += int.Parse(text);
Console.WriteLine($"'{text}': counted");
}
// A catch clause with a type handles exceptions of that type.
catch (FormatException)
{
Console.WriteLine($"'{text}': not a number, skipped");
}
// A catch clause without a type handles every other exception. It must come last.
catch
{
Console.WriteLine($"'{text}': could not be counted, skipped");
}
}

Console.WriteLine($"Total: {total}");

Common Mistakes​

MistakeWhat happensDo this instead
Putting a clause after the general onecatch (FormatException) below catch didn't build: error CS1017: Catch clauses cannot follow the general catch clause of a try statementPut the general catch clause last, after every clause with a type
Reading the exception in a general catch clausee.Message inside catch didn't build: error CS0103: The name 'e' does not exist in the current contextWhen you need the exception, give it a name: catch (Exception e). The FAQ shows what that printed
Hiding a bugA bug in the try block, counts[i + 1], read past the end of the array. The general catch clause reported it as '12': could not be counted, skipped, and the total was wrong: Total: 12. With only catch (FormatException) and catch (OverflowException), the same bug stopped the program with System.IndexOutOfRangeException: Index was outside the bounds of the array.Catch the types you expect, so a bug shows up. Code analysis rule CA1031 warns about this: Catching general exception types can hide runtime problems from the library user and can make debugging more difficult.

FAQ​

What's the difference between catch and catch (Exception e)?​

catch (Exception e) catches every exception that C# code throws too, because each one has to be an Exception: In a throw e; statement, the result of expression e must be implicitly convertible to System.Exception. It also gives you the exception in e. With it, the same counts printed each exception's type and message:

Output
'four': FormatException: The input string 'four' was not in a correct format.
'99999999999': OverflowException: Value was either too large or too small for an Int32.

The specification notes one more difference: a general catch clause is semantically different from one that specifies the type System.Exception, in that the former might also catch exceptions from other languages. C# code can't throw those, though: such exceptions could never be generated by C# code.

Can a general catch clause pass the exception on?​

Yes, with throw; at the end of the block. CA1031 lists that as one of its fixes: To fix a violation of this rule, catch a more specific exception, or rethrow the general exception as the last statement in the catch block. Here the general clause prints a line and rethrows, and a try around it catches the same exception:

Program.cs (a general catch clause that rethrows)
string text = "99999999999";
try
{
try
{
Console.WriteLine(int.Parse(text));
}
catch
{
Console.WriteLine($"'{text}' could not be counted");
throw;
}
}
catch (Exception e)
{
Console.WriteLine($"The outer try caught {e.GetType().Name}");
}
Output
'99999999999' could not be counted
The outer try caught OverflowException

Conclusion​

A catch clause without a type catches every exception that the clauses above it don't. It has to be the last clause and it can't read the exception, so use catch (Exception e) when you need the details. Catch the types you expect first, because a clause that catches everything catches your bugs too.

Additional Resources​