In the world of programming, errors are inevitable. They can occur due to various reasons such as invalid user input, unexpected data formats, or system limitations. Handling these errors gracefully is crucial for building robust applications. In C#, exceptions provide a structured way to handle runtime errors.
Exceptions are events that disrupt the normal flow of a program's execution. When an error occurs, an exception object is created and thrown. The program can then catch this exception and handle it appropriately, preventing the application from crashing.
C# uses a try-catch-finally block structure for handling exceptions. Here’s how it works:
Let's start with a simple example where we divide two numbers and handle any potential division by zero error.
1using System;23class Program4{5static void Main()6{7try8{9Console.Write("Enter the first number: ");10int num1 = Convert.ToInt32(Console.ReadLine());1112Console.Write("Enter the second number: ");13int num2 = Convert.ToInt32(Console.ReadLine());1415int result = num1 / num2;16Console.WriteLine($"The result is {result}");17}18catch (DivideByZeroException ex)19{20Console.WriteLine("Error: Cannot divide by zero.");21}22}23}
In this example:
try block contains the code that might throw a DivideByZeroException.catch block catches the exception and prints an error message.You can have multiple catch blocks to handle different types of exceptions. Here’s an example:
1using System;23class Program4{5static void Main()6{7try8{9Console.Write("Enter the first number: ");10int num1 = Convert.ToInt32(Console.ReadLine());1112Console.Write("Enter the second number: ");13int num2 = Convert.ToInt32(Console.ReadLine());1415int result = num1 / num2;16Console.WriteLine($"The result is {result}");17}18catch (DivideByZeroException ex)19{20Console.WriteLine("Error: Cannot divide by zero.");21}22catch (FormatException ex)23{24Console.WriteLine("Error: Invalid input format.");25}26}27}
In this example:
catch block handles DivideByZeroException.catch block handles FormatException, which occurs if the user inputs a non-numeric value.The finally block is used to execute code that should run regardless of whether an exception was thrown or not. This is often used for cleanup activities like closing files or releasing resources.
1using System;23class Program4{5static void Main()6{7try8{9Console.Write("Enter the first number: ");10int num1 = Convert.ToInt32(Console.ReadLine());1112Console.Write("Enter the second number: ");13int num2 = Convert.ToInt32(Console.ReadLine());1415int result = num1 / num2;16Console.WriteLine($"The result is {result}");17}18catch (DivideByZeroException ex)19{20Console.WriteLine("Error: Cannot divide by zero.");21}22finally23{24Console.WriteLine("Execution completed.");25}26}27}
In this example:
finally block executes after the try and catch blocks, regardless of whether an exception was thrown.In the next section, we will explore more advanced error handling techniques in C#, including custom exceptions and using the throw keyword to rethrow exceptions. Stay tuned!
Info
Understanding how to handle exceptions is crucial for writing reliable and maintainable code. Practice by implementing exception handling in your own projects.