Exception handling in C# is a mechanism that allows developers to manage runtime errors in a controlled way. It helps to maintain the normal flow of the application even when an unexpected situation arises. The primary keywords used for exception handling in C# are try
, catch
, finally
, and throw
.
Basic Structure of Exception Handling
Here's the basic structure of exception handling in C#:
csharp1try 2{ 3 // Code that may throw an exception 4} 5catch (ExceptionType ex) 6{ 7 // Code to handle the exception 8} 9finally 10{ 11 // Code that will run regardless of whether an exception occurred or not 12}
Example 1: Basic Exception Handling
In this example, we will demonstrate a simple division operation that handles a potential division by zero exception.
csharp1using System; 2 3class Program 4{ 5 static void Main() 6 { 7 try 8 { 9 Console.WriteLine("Enter a number to divide 100:"); 10 int number = Convert.ToInt32(Console.ReadLine()); 11 int result = 100 / number; 12 Console.WriteLine($"Result: {result}"); 13 } 14 catch (DivideByZeroException ex) 15 { 16 Console.WriteLine("Error: Cannot divide by zero."); 17 } 18 catch (FormatException ex) 19 { 20 Console.WriteLine("Error: Invalid input format. Please enter a valid number."); 21 } 22 catch (Exception ex) 23 { 24 Console.WriteLine($"An unexpected error occurred: {ex.Message}"); 25 } 26 finally 27 { 28 Console.WriteLine("Execution completed."); 29 } 30 } 31}
Explanation
- try block: Contains the code that may throw an exception (in this case, the division operation).
- catch blocks: These catch specific exceptions. If a
DivideByZeroException
occurs, the corresponding catch block executes. If the input is not a valid integer, aFormatException
is caught. The generalcatch
block catches any other exceptions. - finally block: This block executes regardless of whether an exception occurred or not. It is often used for cleanup code.
Example 2: Throwing Exceptions
You can also throw exceptions manually using the throw
keyword. This is useful for validating conditions.
csharp1using System; 2 3class Program 4{ 5 static void Main() 6 { 7 try 8 { 9 int number = GetPositiveNumber(); 10 Console.WriteLine($"You entered: {number}"); 11 } 12 catch (ArgumentOutOfRangeException ex) 13 { 14 Console.WriteLine(ex.Message); 15 } 16 finally 17 { 18 Console.WriteLine("Execution completed."); 19 } 20 } 21 22 static int GetPositiveNumber() 23 { 24 Console.WriteLine("Enter a positive number:"); 25 int number = Convert.ToInt32(Console.ReadLine()); 26 27 if (number <= 0) 28 { 29 throw new ArgumentOutOfRangeException("number", "The number must be positive."); 30 } 31 32 return number; 33 } 34}
Explanation
- GetPositiveNumber Method: Prompts the user for a number and checks if it is positive. If not, it throws an
ArgumentOutOfRangeException
. - Main Method: Calls
GetPositiveNumber
and handles the exception if it is thrown.
Example 3: Custom Exception
You can create your own exception classes by inheriting from the Exception
class.
csharp1using System; 2 3public class InvalidAgeException : Exception 4{ 5 public InvalidAgeException(string message) : base(message) { } 6} 7 8class Program 9{ 10 static void Main() 11 { 12 try 13 { 14 SetAge(-1); 15 } 16 catch (InvalidAgeException ex) 17 { 18 Console.WriteLine(ex.Message); 19 } 20 finally 21 { 22 Console.WriteLine("Execution completed."); 23 } 24 } 25 26 static void SetAge(int age) 27 { 28 if (age < 0) 29 { 30 throw new InvalidAgeException("Age cannot be negative."); 31 } 32 Console.WriteLine($"Age set to {age}"); 33 } 34}
Explanation
- Custom Exception:
InvalidAgeException
inherits fromException
. It can be used to indicate a specific error condition related to age. - SetAge Method: Validates the age and throws
InvalidAgeException
if the age is negative. - Main Method: Calls
SetAge
and handles the custom exception.
Exception Classes in C#
Exception Class | Description |
---|---|
System.Exception | The base class for all exceptions in .NET. |
System.SystemException | The base class for predefined system exceptions. |
System.ApplicationException | The base class for application-defined exceptions. |
System.ArgumentException | Thrown when one of the arguments provided to a method is not valid. |
System.ArgumentNullException | Thrown when a null reference is passed to a method that does not accept it. |
System.ArgumentOutOfRangeException | Thrown when the value of an argument is outside the allowable range. |
System.DivideByZeroException | Thrown when an attempt is made to divide by zero. |
System.FormatException | Thrown when the format of an argument is invalid. |
System.IndexOutOfRangeException | Thrown when an index is outside the bounds of an array or collection. |
System.InvalidOperationException | Thrown when a method call is invalid for the object's current state. |
System.NullReferenceException | Thrown when there is an attempt to dereference a null object reference. |
System.IO.IOException | The base class for exceptions that occur during input/output operations. |
System.IO.FileNotFoundException | Thrown when an attempt to access a file that does not exist on disk fails. |
System.IO.DirectoryNotFoundException | Thrown when part of a file or directory cannot be found. |
System.Net.WebException | Thrown when an error occurs while accessing the network. |
System.Security.SecurityException | Thrown when a security error is detected. |
System.TimeoutException | Thrown when a timeout occurs while waiting for a process to complete. |
System.InvalidCastException | Thrown when an invalid cast is attempted. |
System.NotSupportedException | Thrown when an operation is not supported. |
System.OperationCanceledException | Thrown when an operation is canceled. |
System.StackOverflowException | Thrown when the execution stack overflows due to excessive recursion. |
System.OutOfMemoryException | Thrown when there is not enough memory to continue the execution of a program. |