Introduction
In this post, we will explore the fundamentals of exception handling in C#. You will learn about the built-in keywords such as try
, catch
, finally
, and throw
that C# provides to handle exceptions effectively. Understanding how to manage exceptions is key to building resilient applications that can address unexpected issues during runtime.
What is Exception Handling?
Exception handling is a programming construct in languages like C# that helps manage errors that occur during the execution of a program. It provides a way to transfer control from one part of a program to another when an error occurs.
Basic Exception Handling Using try, catch, and finally
The try
block wraps the code that may throw an exception, while catch
blocks are used to handle the error. The finally
block contains code that runs regardless of whether an exception occurs.
Example:
public class Program { static void Main() { try { Console.WriteLine("Enter a number to divide 100: "); int divisor = Convert.ToInt32(Console.ReadLine()); int result = 100 / divisor; Console.WriteLine("Result: " + result); } catch (DivideByZeroException) { Console.WriteLine("Cannot divide by zero, please provide a valid number."); } catch (FormatException) { Console.WriteLine("Not a valid number, please enter an integer."); } finally { Console.WriteLine("Execution completed."); } } }
Explanation: This example demonstrates how to handle different types of exceptions separately. It also shows how finally
is used to execute code after try and catch blocks.
Using Specific Exceptions
C# has many built-in exception types like NullReferenceException
, InvalidOperationException
, and others, which you can catch specifically to handle different error conditions.
Creating and Throwing Custom Exceptions
Sometimes, you may need to create your own exception types to handle situations specific to your application.
Example:
public class InvalidUserInputException : Exception { public InvalidUserInputException(string message) : base(message) { } } public class Program { static void ValidateUserInput(string input) { if (string.IsNullOrWhiteSpace(input)) { throw new InvalidUserInputException("Input cannot be empty."); } Console.WriteLine("Input Validated: " + input); } static void Main() { try { Console.WriteLine("Enter your name:"); string input = Console.ReadLine(); ValidateUserInput(input); } catch (InvalidUserInputException ex) { Console.WriteLine("Error: " + ex.Message); } } }
Explanation: This example shows how to create and use a custom exception. Custom exceptions provide a clearer indication of what went wrong in your application.
Conclusion
Exception handling is essential for creating error-resistant programs that prevent unexpected crashes and provide useful error messages to users. This post has equipped you with the knowledge to manage exceptions effectively in your C# applications.