using System;
class Program
{
public static void Main()
{
try
{
// メソッドに想定外の値を渡す
CheckRange(100);
Console.WriteLine("↑でエラーになりここは実行されない");
}
catch (Exception ex)
{
// エラーの場合の例外処理
Console.WriteLine("Mainメソッドでエラーが発生!!!");
Console.WriteLine(ex);
}
}
public static void CheckRange(int value)
{
// 引数のチェック
if (!(value >= 0 && value <= 10))
{
throw new Exception("CheckRangeの引数は0~10の間で指定してください。");
}
}
}
Mainメソッドでエラーが発生!!!
System.Exception: 引数は0~10の間で指定してください。
at Program.CheckRange(Int32 value) in d:\source\repos\test\Program.cs:line 24
at Program.Main() in d:\source\repos\test\Program.cs:line 9
object obj = null;
string str = obj as string ?? throw new Exception("Nullはダメ");
三項演算子
三項演算子の戻り値を返す部分2か所どちらかにthrowが使えます。
int x = 10;
int y = (x >= 0) ? x : throw new Exception();
int z = (x == 5) ? throw new Exception() : x;
switch式
switch式の戻り値を返す部分にthrowが使えます。
int i = 10;
var message = i switch
{
1 => "iが1はOK",
2 => throw new ArgumentException("2はダメ"),
3 => "iが3はOK",
_ => throw new ArgumentException("1と3以外はだめ")
};