How to handle invalid argument in C#

3 Answers

0 votes
using System;

class Program
{
    public static void SetAge(int age) {
        if (age < 0 || age > 120) {
            throw new ArgumentException("Age must be between 0 and 120.");
        }
        
        Console.WriteLine($"Age set to {age}");
    }

    static void Main()
    {
        SetAge(121);
    }
}



/*
run:

ERROR!

Unhandled Exception:
System.ArgumentException: Age must be between 0 and 120.

*/

 



answered May 20, 2025 by avibootz
0 votes
using System;

class Program
{
    public static void SetName(string name) {
        if (string.IsNullOrWhiteSpace(name)) {
            throw new ArgumentNullException(nameof(name), "Name cannot be null or empty.");
        }
        Console.WriteLine($"Name set to {name}");
    }

    static void Main()
    {
        SetName("");
    }
}



/*
run:

RROR!

Unhandled Exception:
System.ArgumentNullException: Name cannot be null or empty.
Parameter name: name

*/

 



answered May 20, 2025 by avibootz
0 votes
using System;

class Program
{
    public static void ProcessInput(string input) {
        try
        {
            if (string.IsNullOrEmpty(input)) {
                throw new ArgumentException("Input cannot be null or empty.");
            }
            Console.WriteLine($"Processing input: {input}");
        }
        catch (ArgumentException ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }


    static void Main()
    {
        ProcessInput("");
    }
}



/*
run:

Error: Input cannot be null or empty.

*/

 



answered May 20, 2025 by avibootz

Related questions

4 answers 334 views
4 answers 354 views
4 answers 314 views
4 answers 294 views
3 answers 246 views
3 answers 248 views
...