VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/exception-handling-in-c-sharp/

⇱ Exception Handling in C# - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Exception Handling in C#

Last Updated : 20 Apr, 2026

In C#, exception handling is the process of responding to runtime anomalies, called exceptions, in a controlled way. Proper handling ensures that a program continues to run or exits gracefully instead of crashing unexpectedly. C# provides structured exception handling using the keywords try, catch, finally, and throw.

Syntax:

try{
// Code that may throw an exception
}

catch (ExceptionType ex){
// Code to handle the exception
}

finally{
// Code that will always execute
}

Keywords for Exception Handling

1. try

The try block contains the code that might throw an exception. Only the code inside the try block is monitored for exceptions.


Output
Division by zero detected.

Explanation:

  • The division uses a variable (x), so the error occurs at runtime, allowing the try-catch block to handle the DivideByZeroException.
  • Only code in try is monitored for exceptions.

2. catch

The catch block handles exceptions thrown in the try block. You can have multiple catch blocks to handle different exception types.

Output

Cannot divide by zero.

Explanation:

  • The first matching catch block handles the exception.
  • The second catch (Exception) acts as a fallback for any other exceptions.

3. finally

The finally block is mainly used for cleanup tasks such as closing files, releasing unmanaged resources, or freeing external connections.

Output

Cannot divide by zero.

Execution completed.

Explanation:

  • Even if no exception occurs, the code in finally runs.
  • Ensures essential cleanup operations are performed.

4. throw

The throw keyword is used to manually raise an exception. It can be used to signal that an error or invalid condition has occurred.

Explanation:

  • throw creates an exception object and passes it up the call stack.
  • The exception can be caught by a try-catch block in the calling code.

Example: Handling Division by Zero

Output:

Error: Division by zero is not allowed.
Execution of try-catch block finished.

Explanation:

  • The try block contains the risky code.
  • The catch block handles the specific exception.
  • The finally block executes irrespective of an exception, ensuring cleanup or final actions.

Multiple Catch Blocks

C# allows multiple catch blocks to handle different types of exceptions:

Output:

Array index is out of range.

Key Points

  • Exception handling prevents programs from crashing due to runtime errors.
  • Use specific exceptions in catch blocks for more precise error handling.
  • The finally block is optional but useful for cleanup.
  • Use throw to raise exceptions intentionally for invalid conditions.
Comment

Explore