Throwing Exceptions in c#
In the C# programming language, exception errors are typically thrown when a user-defined program displays an error that prevents the current program from recovering from the error. C# users can use the throw keyword in their program source code to throw custom, user-defined, manual exception errors. Throwing any type of exception in a program serves as an indication that an error exception has been generated in the current program, and provides a mechanism for handling and managing an error exception in the call stack top order.

Syntax for throwing an exception in a C# program.
throw new Exception(“Display Error message”);
element of throwing an exception.
- throw – Here, the throw keyword is used to throw an exception error in a program.
- new Exception(“Display Error message”) – This creates a new instance of an exception error in the current program. In this case, it is a generic program exception. However, it could be any type of special exception error in the current program, such as ArgumentNullException, DivideByZeroException, etc.
Types of Exceptions in C#.
- Custom Exception – C# programmers can throw different types of program exceptions based on the type of exception error signal they want to display in a program.
- Exception – This is the base class for all types of exceptions in a C# program. Exceptions can be used in programs when a special user-defined program exception class does not accommodate a particular error case.
- ArgumentNullException – This exception is generated in a program when a user-defined class method receives a null argument value, which is not permitted to perform null behavior in that program.
- ArgumentOutOfRangeException – This exception is displayed in a program when a class method receives an argument value that is outside the current class’s allowed range.
- InvalidOperationException – This exception is generated in a program when a programming operation is invalid for the object’s current state.
- FileNotFoundException – This exception is generated in a program when a file stored in the current program cannot be found.
- IOException – This exception is generated in a C# program to preview an exception error during I/O (input/output) file operations, such as reading and writing a file in file handling.
A basic example of throwing an exception in a C# program.
So, let’s create an example in C# programming where we can manually throw a program exception error when a user input value is invalid.
using System;
class Program
{
static void Main()
{
try
{
int output = distributeIntegers(30, 0); // This will throw a program exception
Console.WriteLine(“Display output – ” + output);
}
catch (DivideByZeroException excption)
{
Console.WriteLine(“Display Error – ” + exception.Message);
}
}
static int distributeIntegers(int fraction, int divisor)
{
if (divisor == 0)
{
throw new DivideByZeroException(“The divisor value will never be zero.”);
}
return fraction / divisor;
}
}
Explanation in the throwing exception example.
- In this example, the distributeIntegers method checks whether the divisor value is 0. If so, the method throws a DivideByZeroException exception.
- Then, the program error exception is caught in the catch block in the Main method, and an error message is displayed.
Creating a Custom Exception in a C# Program.
C# programmers can also create their own custom exception error class to handle specific exception errors in their program applications. A custom exception class in C# is typically inspired by a base exception class.
Creating a Custom Exception in C#.
using System;
public class InsufficientAmountException : Exception
{
public InsufficientAmountException() { }
public InsufficientAmountException(string info)
: base(info) { }
public InsufficientAmountException(string info, Exception inner)
: base(info, inner) { }
}
Custom Exception explanation.
- The custom exception class InsufficientAmountException can be used in this program condition to indicate or display a specific exception error. For example, when a user attempts to withdraw more money than is currently deposited in their account.
Example of using a custom exception in C#.
Using System;
// here we create a Custom Exception Class
class InsufficientDepositException : Exception
{
public InsufficientDepositException(string Message) : base(Message)
{
}
}
class program
{
static void Main()
{
try
{
Withdraw(9999, 21000); // here This will throw a custom user exception
}
catch (InsufficientDepositException exception)
{
Console.WriteLine(“Display Error: ” + exception.Message);
}
}
static void Withdraw(decimal balance, decimal withdrawalAmount)
{
if (withdrawalAmount > balance)
{
throw new InsufficientDepositException (“No enough amount for withdrawal.”);
}
Console.WriteLine(“Amount Withdrawal transaction successful.”);
}
}
Here’s the custom exception.
- In the above program, the Withdraw method checks whether the user’s withdrawal amount is greater than the current deposit balance.
- If this happens, it throws an InsufficientDepositException error, which is caught in a user-defined catch block.
Rethrowing Exceptions in C#.
If C# programmers want to manage or handle rethrowing exception errors in their program, C# users can rethrow their caught Program Error exception, and then pass it back to another catch block or caller in the call stack.
Example of rethrowing a C# exception.
using System;
class Program
{
static void Main()
{
try
{
ManageData();
}
catch (Exception exception)
{
Console.WriteLine(“Exception Catch in Start data – ” + exception.Message);
}
}
static void ManageData()
{
try
{
// here it simulates a program exception error
throw new InvalidOperationException(“Display issue when processing manage data.”);
}
catch (InvalidOperationException exception)
{
Console.WriteLine(“Exception Catch in Manage Data – ” + exception.Message);
throw; // here it rethrows the caught exception error
}
}
}
}
Rethrowing Exceptions Example Explanation.
- In this program, the ManageData method throws an InvalidOperationException, which is caught in the catch block.
- Then, the exception is rethrown using the throw keyword. This allows it to be caught by an external catch block in the Main method.
Throwing exceptions in conditional logic in C#.
C# programmers can also throw a conditional logic program exception error based on some specific conditional logic in their program source code.
using System;
class Program
{
static void Main()
{
try
{
TestAge(20); // Here we set the stu_age below the legal threshold parameter
}
catch (ArgumentException excpton)
{
Console.WriteLine(excpton.Message);
}
}
static void TestAge(int stu_age)
{
if (stu_age < 27)
{
throw new ArgumentException(“Here Student Age at least 27 or older to process.”);
}
Console.WriteLine(“Student permission provided.”);
}
}
Throwing exceptions in conditional logic example explanation.
- In this program, the stu_age method throws an ArgumentException program exception error message if the student’s age is less than 27 years old. This ensures that only students with a student age of at least 27 or older are printed to the process message statement.
Throwing Exceptions Summary in C#.
- Throwing exception errors in any C# program allows you to indicate program errors that require special handling.
- C# users can throw built-in program exceptions, such as ArgumentNullException, InvalidOperationException, etc., or custom program exception errors.
- If a program needs to pass exceptions up the call stack, you can rethrow them using the throw keyword.
