What is ArgumentException in C#: Explanation and Example
ArgumentException in C# is an error type that happens when a method receives an argument that is not valid. It helps programmers catch mistakes where input values do not meet the expected rules or conditions.How It Works
Imagine you are filling out a form and you enter a wrong value, like a negative age. The program needs a way to say "Hey, this value doesn't make sense here!" In C#, ArgumentException is like that alert. It is a special kind of error that a method throws when the input it gets is not right.
When a method expects certain rules for its inputs, like a positive number or a non-empty string, it can check the arguments and throw ArgumentException if the rules are broken. This stops the program from continuing with bad data and helps developers find and fix the problem quickly.
Example
This example shows a method that requires a positive number. If the number is zero or negative, it throws an ArgumentException with a clear message.
using System; class Program { static void CheckPositive(int number) { if (number <= 0) { throw new ArgumentException("Number must be positive", nameof(number)); } Console.WriteLine($"Number {number} is valid."); } static void Main() { try { CheckPositive(5); // Valid input CheckPositive(-3); // Invalid input } catch (ArgumentException ex) { Console.WriteLine($"Error: {ex.Message}"); } } }
When to Use
Use ArgumentException when you want to make sure that the inputs to your methods are correct and meaningful. It is helpful in situations where a method cannot work properly with bad data.
For example, if you have a method that calculates the square root of a number, you should throw ArgumentException if the input is negative because square roots of negative numbers are not handled in that method.
This helps catch errors early and makes your code more reliable and easier to debug.
Key Points
- ArgumentException signals invalid method arguments.
- It stops execution when input rules are broken.
- Use it to make your code safer and clearer.
- Always provide a helpful message explaining the problem.