Skip to content

JA CSharp Keyword throw

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: throw

ディレクトリ C# · 実践的な指導

例外をスローまたは再スローします。投げる; catch には初期スタックが格納されます。

簡単な例 (Example.cs)

この例を Example.cs として別に保存し、このページの他の例とは独立して実行してください。

Example.cs:

// PROJECT-EXAMPLE
try { throw new System.InvalidOperationException("Stop"); }
catch (System.InvalidOperationException error) { System.Console.WriteLine(error.Message); }

結果:

Stop

構文

throw new Exception(...); / throw;

例 1: 基本形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        try { int number = int.Parse("invalid"); Console.WriteLine(number); }
        catch (FormatException error) { Console.WriteLine(error.Message); }
        finally { Console.WriteLine("Finished"); }
    }
}

例 2: 別の実用的な形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        try { Validation.Positive(-1); }
        catch (ArgumentOutOfRangeException error) when (error.ParamName == "value") { Console.WriteLine("Negative value"); }
        finally { Console.WriteLine("Cleanup"); }
    }
}
public static class Validation { public static void Positive(int value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value)); } }

公式ソース: Microsoft Learn。

Clone this wiki locally