計算機科学のブログ

exception handling - Putting out fires gets old - Overflow, Null Reference, Invalid Cast, Divide By Zero, Format

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.625(Sharpen your pencil)の解答を求めてみる。

コード

Program.cs

using ConsoleApp1;

object myBee = new HoneyBee(36.5, "Zippo");
// 3. System.InvalidCastException
// float howMuchHoney = (float)myBee;
HoneyBee anotherBee = new HoneyBee(12.5, "Buzzy");
// 5. System.FormatException
// double beeName = double.Parse(anotherBee.Name);
double totalHoney = 36.5 + 12.5;
string beesWeCanFeed = "";
for (int i = 0; i < (int)totalHoney; i++)
{
    beesWeCanFeed += i.ToString();
}
// 5. System.OverFlowException
// int numberOfBees = int.Parse(beesWeCanFeed);

// int drones = 4;
// int queens = 0;
// 4. Sysntem.DivideByZeroException
// int dronesPerQueen = drones / queens;
int dronesPerQueen = 11;
// anotherBee = null;
if (dronesPerQueen > 10)
{
    // 2. System.NullReferenceException
    anotherBee.Capacity = 12.6;
}

HoneyBee.cs

namespace ConsoleApp1;

public class HoneyBee(double capacity, string name)
{
    public double Capacity { get; set; } = capacity;
    public string Name { get; set; } = name;
}

入出力結果(Terminal, Zsh)

% dotnet run
Unhandled exception. System.InvalidCastException: Unable to cast object of type 'ConsoleApp1.HoneyBee' to type 'System.Single'.
   at Program.<Main>$(String[] args) in /…/ConsoleApp1/Program.cs:line 5
% dotnet run
Unhandled exception. System.FormatException: The input string 'Buzzy' was not in a correct format.
   at System.Number.ThrowFormatException[TChar](ReadOnlySpan`1 value)
   at System.Double.Parse(String s)
   at Program.<Main>$(String[] args) in /…/ConsoleApp1/Program.cs:line 8
% dotnet run
Unhandled exception. System.OverflowException: Value was either too large or too small for an Int32.
   at System.Number.ThrowOverflowException[TInteger]()
   at System.Int32.Parse(String s)
   at Program.<Main>$(String[] args) in /…/ConsoleApp1/Program.cs:line 16
% dotnet run
Unhandled exception. System.DivideByZeroException: Attempted to divide by zero.
   at Program.<Main>$(String[] args) in /…/ConsoleApp1/Program.cs:line 21
% dotnet run
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at Program.<Main>$(String[] args) in /…/ConsoleApp1/Program.cs:line 27
% dotnet run
%