c-sharp
  1. c-sharp-try-catch

C# Try/Catch Page

Syntax

try {
    // try block
} catch (Exception e) {
    // catch block
}

Example

try {
    int a = 10;
    int b = 0;
    int result = a / b;
} catch (DivideByZeroException e) {
    Console.WriteLine("Cannot divide by zero.");
}

Output

Cannot divide by zero.

Explanation

In C#, the try/catch block is used for error handling. The code that might throw an exception is surrounded by the try block, and the code that handles the exception is within the catch block. If an exception is thrown within the try block, the program execution will immediately jump to the catch block.

In the example above, we are dividing the integer value a by 0. Since dividing by 0 results in an exception, the executed code will jump to the catch block where the message "Cannot divide by zero." will be outputted.

Use

The try/catch block is used for error handling in C#. It is used when there is a possibility of an exception being thrown in the code, and you want to handle it gracefully by creating a fallback or alternate method of operation. The try/catch block is also useful to ensure that a program does not crash due to an unexpected exception.

Important Points

  • The try/catch block is used for error handling in C#.
  • The code that might throw an exception is within the try block, and the code that handles the exception is within catch block.
  • If an exception is thrown within the try block, the program execution will immediately jump to the catch block.
  • The try/catch block is useful to ensure that a program does not crash due to an unexpected exception.

Summary

The try/catch block is a crucial part of C# code when it comes to error handling. It allows you to gracefully handle exceptions and ensures that a program does not crash unexpectedly. The try/catch block uses a try block to encompass the code that might trigger an exception, and the catch block to contain error handling code. With the try/catch block, a C# programmer can create robust and stable applications.

Published on: