exception handling - Putting out fires gets old - try/catch/finally
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.639(Pool Puzzle)の解答を求めてみる。
コード
Program.cs
using ConsoleApp1;
Kangaroo joey = new();
int koala = joey.Wombat(joey.Wombat(joey.Wombat(1)));
try
{
Console.WriteLine((15 / koala) + " eggs per pound");
}
catch (DivideByZeroException)
{
Console.WriteLine("G'Day Mate!");
}
Kangaroo.cs
namespace ConsoleApp1;
public class Kangaroo
{
FileStream? fs;
int croc;
int dingo = 0;
public int Wombat(int wallaby)
{
croc = wallaby;
try
{
if (croc > 0)
{
fs = File.OpenWrite("wobbiegong");
croc = 0;
}
else if (croc < 0)
{
croc = 3;
}
else
{
fs = File.OpenRead("wobbiegong");
croc = 1;
}
}
catch (IOException)
{
croc = 3;
}
catch
{
croc = 4;
}
finally
{
if (croc > 2)
{
croc = dingo;
}
}
return croc;
}
}
入出力結果(Terminal, Zsh)
% dotnet run
G'Day Mate!
%