Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
try keyword in C#
The try keyword in C# is used to define a block of code that might throw an exception. It must be followed by one or more catch blocks to handle exceptions, and optionally a finally block for cleanup code that runs regardless of whether an exception occurs.
Syntax
Following is the basic syntax for a try-catch block −
try {
// code that might throw an exception
}
catch (ExceptionType e) {
// exception handling code
}
Following is the syntax with a finally block −
try {
// code that might throw an exception
}
catch (ExceptionType e) {
// exception handling code
}
finally {
// cleanup code that always executes
}
How It Works
When an exception occurs within a try block, the program control immediately transfers to the appropriate catch block. The finally block, if present, always executes whether an exception occurs or not, making it ideal for cleanup operations.
Using Try-Catch for Division by Zero
Example
using System;
class Demo {
int result;
public Demo() {
result = 0;
}
public void Division(int val1, int val2) {
try {
result = val1 / val2;
Console.WriteLine("Division successful");
}
catch (DivideByZeroException e) {
Console.WriteLine("Exception caught: {0}", e.Message);
}
finally {
Console.WriteLine("Result: {0}", result);
}
}
public static void Main(string[] args) {
Demo d = new Demo();
d.Division(100, 0);
d.Division(100, 5);
}
}
The output of the above code is −
Exception caught: Attempted to divide by zero. Result: 0 Division successful Result: 20
Using Multiple Catch Blocks
Example
using System;
class MultipleExceptions {
public static void Main(string[] args) {
int[] numbers = {10, 20, 30};
try {
Console.WriteLine("Accessing array element: " + numbers[5]);
int result = 10 / 0;
}
catch (IndexOutOfRangeException e) {
Console.WriteLine("Array index error: " + e.Message);
}
catch (DivideByZeroException e) {
Console.WriteLine("Division error: " + e.Message);
}
catch (Exception e) {
Console.WriteLine("General exception: " + e.Message);
}
finally {
Console.WriteLine("Cleanup completed");
}
}
}
The output of the above code is −
Array index error: Index was outside the bounds of the array. Cleanup completed
Using Try-Finally Without Catch
Example
using System;
class TryFinally {
public static void Main(string[] args) {
try {
Console.WriteLine("Executing code in try block");
int result = 10 / 2;
Console.WriteLine("Result: " + result);
}
finally {
Console.WriteLine("Finally block always executes");
}
}
}
The output of the above code is −
Executing code in try block Result: 5 Finally block always executes
Key Rules
-
A
tryblock must be followed by at least onecatchorfinallyblock. -
Multiple
catchblocks can handle different exception types, but more specific exceptions should come before general ones. -
The
finallyblock executes regardless of whether an exception occurs or not. -
Control never returns to the
tryblock once an exception is thrown.
Conclusion
The try keyword in C# enables robust exception handling by defining blocks of code that might throw exceptions. Combined with catch and finally blocks, it provides a structured approach to handle errors gracefully and ensure proper cleanup of resources.
