C# Exceptions – Try..Catch

C# Tutorial

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 exception

  • catch → Handles the exception

  • finally → Always executes, used for cleanup


 Basic Example


Output:

Error: Attempted to divide by zero.
This block always executes.

 Multiple Catch Blocks

You can handle different exceptions separately:


 Catching All Exceptions


Exception is the base class for all exceptions.


 Using Finally

  • finally block always executes, even if no exception occurs

  • Useful 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..catch handles exceptions

  • finally executes always

  • Use specific exceptions first, general exceptions later

  • Can throw custom exceptions for validation

You may also like...