Exceptions and Defensive Coding
Throw and Catch
A method can throw an exception and a caller can catch it.
throw
`throw` reports a problem that the caller should handle.
Throw and Catch
ThrowCatch.cs
Replay: real traced execution (multi-file project)
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 = 16;
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 = -1;
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 = 21;
string group = "unknown";
try
{
group = AgeGroup(age);
}
catch (ArgumentException)
{
group = "invalid";
}
Console.WriteLine($"age={age}");
Console.WriteLine($"group={group}");
}
}
age ← 16, group ← unknown
20static void Main()21{22 int age→ 16 = 16; //@age=-1, 2123 string group→ unknown = "unknown";try
25try26{27 group = AgeGroup(age16);28}static string AgeGroup(int age)
4{5 static string AgeGroup(int age16)6 {7 if (age < 0)if (age < 18)
12if (age16 < 18)13{14 return "minor";15}group ← minor
26{27 group→ minor = AgeGroup(age16);28}Console.WriteLine($"age={age}");
34 Console.WriteLine($"age={age16}");35 Console.WriteLine($"group={groupminor}");36}outputage=16 group=minor
age ← -1, group ← unknown
20static void Main()21{22 int age→ -1 = -1;23 string group→ unknown = "unknown";try
25try26{27 group = AgeGroup(age-1);28}static string AgeGroup(int age)
4{5 static string AgeGroup(int age-1)6 {7 if (age < 0)if (age < 0)
6{7 if (age-1 < 0)8 {9 throw new ArgumentException("age");10 }group ← invalid
28}29catch (ArgumentException)30{31 group→ invalid = "invalid";32}Console.WriteLine($"age={age}");
34 Console.WriteLine($"age={age-1}");35 Console.WriteLine($"group={groupinvalid}");36}outputage=-1 group=invalid
age ← 21, group ← unknown
20static void Main()21{22 int age→ 21 = 21;23 string group→ unknown = "unknown";try
25try26{27 group = AgeGroup(age21);28}static string AgeGroup(int age)
4{5 static string AgeGroup(int age21)6 {7 if (age < 0)8 {9 throw new ArgumentException("age");10 }1112 if (age < 18)13 {14 return "minor";15 }1617 return "adult";18 }group ← adult
26{27 group→ adult = AgeGroup(age21);28}Console.WriteLine($"age={age}");
34 Console.WriteLine($"age={age21}");35 Console.WriteLine($"group={groupadult}");36}outputage=21 group=adult