C# Try Catch Exceptions

In C#, an exception is an error that occurs at runtime and disrupts the normal flow of a program. Exceptions can be caused by various reasons, such as invalid user input, file I/O errors, and other runtime errors. To handle these exceptions and prevent the program from crashing, C# provides a mechanism called try-catch.

The try-catch block

The try-catch block is used to handle exceptions that might occur during the execution of a program. The basic syntax of the try-catch block is as follows:

1try 2{ 3 // code that might throw an exception 4} 5catch (Exception ex) 6{ 7 // code to handle the exception 8}

In this code, any exception that occurs inside the try block will be caught by the catch block. The catch block takes an Exception object as a parameter, which contains information about the exception that occurred. Inside the catch block, you can write code to handle the exception.

Example

Let's say you have a program that reads an integer from the user and then divides it by 0. This will throw a DivideByZeroException exception. To handle this exception, you can use a try-catch block as follows:

1try 2{ 3 Console.Write("Enter an integer: "); 4 int num = int.Parse(Console.ReadLine()); 5 int result = num / 0; 6 Console.WriteLine("The result is: " + result); 7} 8catch (DivideByZeroException ex) 9{ 10 Console.WriteLine("Error: " + ex.Message); 11}

In this code, the try block reads an integer from the user and then tries to divide it by 0. Since dividing by 0 is not allowed, a DivideByZeroException exception is thrown. This exception is caught by the catch block, which prints an error message to the console.

Multiple catch blocks

You can have multiple catch blocks to handle different types of exceptions. For example, if you have a program that reads a file and the file is not found, a FileNotFoundException exception is thrown. You can use a try-catch block with multiple catch blocks to handle this exception as well as any other exceptions that might occur:

1try 2{ 3 using (StreamReader sr = new StreamReader("file.txt")) 4 { 5 string line = sr.ReadLine(); 6 Console.WriteLine(line); 7 } 8} 9catch (FileNotFoundException ex) 10{ 11 Console.WriteLine("Error: File not found - " + ex.FileName); 12} 13catch (Exception ex) 14{ 15 Console.WriteLine("Error: " + ex.Message); 16}

In this code, the try block tries to read a file named "file.txt" and print the first line of the file. If the file is not found, a FileNotFoundException exception is thrown, which is caught by the first catch block. If any other exception occurs, it is caught by the second catch block, which prints a generic error message.