How to Catch Multiple Exceptions in C#
By FoxLearn 12/2/2024 7:49:01 AM 208
In C#, you can catch multiple exceptions in a single catch block by using a few different approaches.
How to Catch Multiple Exceptions in C#?
From C# 7.0 onwards, you can catch multiple exception types in a single catch
block using a pipe (|
) between exception types.
For example, Using catch with Multiple Exception Types (C# 7.0 and later)
try { // Code that may throw exceptions } catch (ArgumentNullException | DivideByZeroException ex) { Console.WriteLine("An exception of type ArgumentNullException or DivideByZeroException was caught: " + ex.Message); }
In C# 6.0 and later, you can use exception filters to catch specific exceptions only if certain conditions are met, making the code more readable and expressive.
For example, Using Exception Filters (C# 6.0 and later)
try { // Code that may throw exceptions } catch (Exception ex) when (ex is ArgumentNullException || ex is DivideByZeroException) { Console.WriteLine("ArgumentNullException or DivideByZeroException caught: " + ex.Message); }
Catching System.Exception
and switching on exception types using is
allows you to catch and handle specific exception types in a controlled manner.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#
Categories
Popular Posts
Motiv MUI React Admin Dashboard Template
11/19/2024
AdminKit Bootstrap 5 HTML5 UI Kits Template
11/17/2024
K-WD Tailwind CSS Admin Dashboard Template
11/17/2024