Exceptions and Defensive Coding
Throw and Catch
A method can throw an exception and a caller can catch it.
Throw and Catch
ThrowCatch.cs
using System;
class Program
{
static string AgeGroup(int age)
{
if (age < 0)
{
throw new ArgumentException("age");
}
if (age < 18)
{
return "minor";
}
return "adult";
}
static void Main()
{
int age = ;
string group = "unknown";
try
{
group = AgeGroup(age);
}
catch (ArgumentException)
{
group = "invalid";
}
Console.WriteLine($"age={age}");
Console.WriteLine($"group={group}");
}
}
using System;
class Program
{
static string AgeGroup(int age)
{
if (age < 0)
{
throw new ArgumentException("age");
}
if (age < 18)
{
return "minor";
}
return "adult";
}
static void Main()
{
int age = ;
string group = "unknown";
try
{
group = AgeGroup(age);
}
catch (ArgumentException)
{
group = "invalid";
}
Console.WriteLine($"age={age}");
Console.WriteLine($"group={group}");
}
}
using System;
class Program
{
static string AgeGroup(int age)
{
if (age < 0)
{
throw new ArgumentException("age");
}
if (age < 18)
{
return "minor";
}
return "adult";
}
static void Main()
{
int age = ;
string group = "unknown";
try
{
group = AgeGroup(age);
}
catch (ArgumentException)
{
group = "invalid";
}
Console.WriteLine($"age={age}");
Console.WriteLine($"group={group}");
}
}
throw
`throw` reports a problem that the caller should handle.