C# Exceptions – Try..Catch

C# Exceptions – Try..Catch
Exceptions in C# are runtime errors that occur during program execution.
The try..catch block is used to handle exceptions and prevent the program from crashing.
Syntax
try→ Contains code that might throw an exceptioncatch→ Handles the exceptionfinally→ Always executes, used for cleanup
Basic Example
Output:
Multiple Catch Blocks
You can handle different exceptions separately:
Catching All Exceptions
✔ Exception is the base class for all exceptions.
Using Finally
finallyblock always executes, even if no exception occursUseful for closing files, database connections, or releasing resources
Throwing Exceptions
You can throw your own exceptions using throw:
Custom Exception
Common Mistakes
❌ Ignoring exceptions (no try..catch)
❌ Catching generic exceptions unnecessarily
❌ Not using finally to release resources
Summary
Exceptions = runtime errors
try..catchhandles exceptionsfinallyexecutes alwaysUse specific exceptions first, general exceptions later
Can throw custom exceptions for validation
