C# TUTORIALS

C# Exception Handling: try, catch, finally and Custom Exceptions

Exception handling lets a C# application respond to unexpected runtime conditions without abruptly terminating the entire operation.

Basic try and catch

try
{
    int value = int.Parse(input);
}
catch (FormatException)
{
    Console.WriteLine("Enter a valid number.");
}

Using finally

The finally block runs after the try/catch flow and is useful for cleanup operations.

try
{
    // Work with a resource
}
finally
{
    // Cleanup
}

Throwing Exceptions

Use throw when the current method cannot continue with invalid state.

if (amount < 0)
    throw new ArgumentOutOfRangeException(nameof(amount));

Custom Exceptions

public class InsufficientBalanceException : Exception
{
    public InsufficientBalanceException(string message)
        : base(message) { }
}

Best Practices

  • Catch specific exceptions rather than Exception when possible.
  • Do not use exceptions for normal control flow.
  • Preserve the original exception when rethrowing with throw;.
  • Include useful context in application logs.
  • Do not expose sensitive exception details to end users.

Conclusion

Good exception handling makes C# applications more reliable and easier to diagnose. Catch only what you can handle and allow unexpected failures to be handled at an appropriate application boundary.

🤖 AlgoLassi Assistant Have a question about this tutorial?

Ask AlgoLassi and get an answer plus the tutorials worth studying next.

Ask a question

đŸ’Ŧ Comments

Sign in with Google to publish immediately, or comment anonymously and wait for approval.

Comments will appear here when available.