Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Master Exception Handling with Try-Catch

- 11.07.26 - ErcanOPAK

🛡️ Exception Handling = Robust Code

Apps crash without error handling. Try-catch handles errors gracefully. Robust, reliable apps.

📝 Try-Catch Basics

try
{
    // Code that might throw
    int result = int.Parse(input);
    Console.WriteLine($"Result: {result}");
}
catch (FormatException ex)
{
    Console.WriteLine($"Invalid format: {ex.Message}");
}
catch (OverflowException ex)
{
    Console.WriteLine($"Number too large: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"Error: {ex.Message}");
    throw;
}
finally
{
    Console.WriteLine("Operation completed");
}

// Using with IDisposable
using (var connection = new SqlConnection(connectionString))
{
    // Auto-disposed
}

🎯 Advanced Patterns

// Custom exception
public class ValidationException : Exception
{
    public ValidationException(string message) : base(message) { }
    public ValidationException(string message, Exception inner) : base(message, inner) { }
}

// Try pattern
public bool TryParseInt(string input, out int result)
{
    try
    {
        result = int.Parse(input);
        return true;
    }
    catch
    {
        result = 0;
        return false;
    }
}

// Exception filters
try
{
    // Some code
}
catch (Exception ex) when (ex is TimeoutException || ex is SqlException)
{
    // Handle specific errors only
}

// Throw with inner exception
try
{
    // Some code
}
catch (Exception ex)
{
    throw new ApplicationException("Failed to process", ex);
}

// Global exception handling
public class GlobalExceptionHandler
{
    public static async Task HandleException(Exception ex, ILogger logger)
    {
        logger.LogError(ex, "Unhandled exception");
        throw ex;
    }
}

✅ Exception Tips

  • Don’t catch exceptions you can’t handle
  • Use specific exception types
  • Log all exceptions with context
  • Use finally for cleanup
  • Use using for IDisposable resources

“Exception handling makes apps robust. Catch, log, recover. Essential for professional C#.”

— Senior Developer

Related posts:

C#: Fix an IAsyncEnumerable That Silently Loads Everything Into Memory Because of One Accidental ToL...

C#: Fix an IAsyncEnumerable That Silently Loads Everything Into Memory Because of One Accidental ToL...

C#: Use ArgumentNullException.ThrowIfNull for Cleaner Validation

C#: Use ArgumentNullException.ThrowIfNull for Cleaner Validation

C#: Use Index and Range for Clean Array Slicing

C#: Use Index and Range for Clean Array Slicing

Views: 5

Post navigation

SQL: Use Subqueries for Complex Data
C#: Use Task-Based Asynchronous Pattern (TAP)

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (661)
  • Add Constraint to SQL Table to ensure email contains @ (619)
  • Average of all values in a column that are not zero in SQL (577)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (553)
  • Find numbers with more than two decimal places in SQL (481)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com