exception handling - Putting out fires gets old - Custom exceptions
Head First C Sharp: A Learner’s Guide to Real-World Programming with C Sharp and .NET (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)の Chapter 12(exception handling - Putting out fires gets old)、p.643(Exception Magnets)の解答を求めてみる。
コード
Program.cs
using ConsoleApp1;
Console.Write("when it ");
ExTestDrive.Zero("yes");
Console.Write(" it ");
ExTestDrive.Zero("no");
Console.WriteLine(".");
MyException.cs
namespace ConsoleApp1;
public class MyException : Exception { }
ExTestDrive.cs
namespace ConsoleApp1;
public class ExTestDrive
{
public static void Zero(string test)
{
Console.Write("t");
try
{
DoRisky(test);
Console.Write("o");
}
catch (MyException)
{
Console.Write("a");
}
finally
{
Console.Write("w");
Console.Write("s");
}
}
static void DoRisky(string t)
{
Console.Write("h");
if (t == "yes")
{
throw new MyException();
}
Console.Write("r");
}
}
入出力結果(Terminal, Zsh)
% dotnet run
when it thaws it throws.
%