C# Exception Handling


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 trycatchfinally, and throw.

Basic Structure of Exception Handling

Here's the basic structure of exception handling in C#:

csharp
1try 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.

csharp
1using 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

  1. try block: Contains the code that may throw an exception (in this case, the division operation).
  2. catch blocks: These catch specific exceptions. If a DivideByZeroException occurs, the corresponding catch block executes. If the input is not a valid integer, a FormatException is caught. The general catch block catches any other exceptions.
  3. 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.

csharp
1using 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

  1. GetPositiveNumber Method: Prompts the user for a number and checks if it is positive. If not, it throws an ArgumentOutOfRangeException.
  2. 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.

csharp
1using 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

  1. Custom ExceptionInvalidAgeException inherits from Exception. It can be used to indicate a specific error condition related to age.
  2. SetAge Method: Validates the age and throws InvalidAgeException if the age is negative.
  3. Main Method: Calls SetAge and handles the custom exception.

Exception Classes in C#

Exception ClassDescription
System.ExceptionThe base class for all exceptions in .NET.
System.SystemExceptionThe base class for predefined system exceptions.
System.ApplicationExceptionThe base class for application-defined exceptions.
System.ArgumentExceptionThrown when one of the arguments provided to a method is not valid.
System.ArgumentNullExceptionThrown when a null reference is passed to a method that does not accept it.
System.ArgumentOutOfRangeExceptionThrown when the value of an argument is outside the allowable range.
System.DivideByZeroExceptionThrown when an attempt is made to divide by zero.
System.FormatExceptionThrown when the format of an argument is invalid.
System.IndexOutOfRangeExceptionThrown when an index is outside the bounds of an array or collection.
System.InvalidOperationExceptionThrown when a method call is invalid for the object's current state.
System.NullReferenceExceptionThrown when there is an attempt to dereference a null object reference.
System.IO.IOExceptionThe base class for exceptions that occur during input/output operations.
System.IO.FileNotFoundExceptionThrown when an attempt to access a file that does not exist on disk fails.
System.IO.DirectoryNotFoundExceptionThrown when part of a file or directory cannot be found.
System.Net.WebExceptionThrown when an error occurs while accessing the network.
System.Security.SecurityExceptionThrown when a security error is detected.
System.TimeoutExceptionThrown when a timeout occurs while waiting for a process to complete.
System.InvalidCastExceptionThrown when an invalid cast is attempted.
System.NotSupportedExceptionThrown when an operation is not supported.
System.OperationCanceledExceptionThrown when an operation is canceled.
System.StackOverflowExceptionThrown when the execution stack overflows due to excessive recursion.
System.OutOfMemoryExceptionThrown when there is not enough memory to continue the execution of a program.

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 trycatchfinally, and throw.

Basic Structure of Exception Handling

Here's the basic structure of exception handling in C#:

csharp
1try 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.

csharp
1using 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

  1. try block: Contains the code that may throw an exception (in this case, the division operation).
  2. catch blocks: These catch specific exceptions. If a DivideByZeroException occurs, the corresponding catch block executes. If the input is not a valid integer, a FormatException is caught. The general catch block catches any other exceptions.
  3. 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.

csharp
1using 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

  1. GetPositiveNumber Method: Prompts the user for a number and checks if it is positive. If not, it throws an ArgumentOutOfRangeException.
  2. 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.

csharp
1using 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

  1. Custom ExceptionInvalidAgeException inherits from Exception. It can be used to indicate a specific error condition related to age.
  2. SetAge Method: Validates the age and throws InvalidAgeException if the age is negative.
  3. Main Method: Calls SetAge and handles the custom exception.

Exception Classes in C#

Exception ClassDescription
System.ExceptionThe base class for all exceptions in .NET.
System.SystemExceptionThe base class for predefined system exceptions.
System.ApplicationExceptionThe base class for application-defined exceptions.
System.ArgumentExceptionThrown when one of the arguments provided to a method is not valid.
System.ArgumentNullExceptionThrown when a null reference is passed to a method that does not accept it.
System.ArgumentOutOfRangeExceptionThrown when the value of an argument is outside the allowable range.
System.DivideByZeroExceptionThrown when an attempt is made to divide by zero.
System.FormatExceptionThrown when the format of an argument is invalid.
System.IndexOutOfRangeExceptionThrown when an index is outside the bounds of an array or collection.
System.InvalidOperationExceptionThrown when a method call is invalid for the object's current state.
System.NullReferenceExceptionThrown when there is an attempt to dereference a null object reference.
System.IO.IOExceptionThe base class for exceptions that occur during input/output operations.
System.IO.FileNotFoundExceptionThrown when an attempt to access a file that does not exist on disk fails.
System.IO.DirectoryNotFoundExceptionThrown when part of a file or directory cannot be found.
System.Net.WebExceptionThrown when an error occurs while accessing the network.
System.Security.SecurityExceptionThrown when a security error is detected.
System.TimeoutExceptionThrown when a timeout occurs while waiting for a process to complete.
System.InvalidCastExceptionThrown when an invalid cast is attempted.
System.NotSupportedExceptionThrown when an operation is not supported.
System.OperationCanceledExceptionThrown when an operation is canceled.
System.StackOverflowExceptionThrown when the execution stack overflows due to excessive recursion.
System.OutOfMemoryExceptionThrown when there is not enough memory to continue the execution of a program.

Talk to us?

Post your blog