本文へスキップ
製品デスクトップツールTASTECAD図面の確認TASTEFILESファイル管理TASTEFTPファイル転送TASTESSHリモートワークスペースTASTEZIP圧縮と展開開発ツールTASTECODERust 統合開発環境TASTESTUDIO統合開発・テスト環境TASTEETLデータ統合(ETL)サーバーTASTEREMOTEリモートデスクトップサーバーTASTEGEO空間情報サーバーTASTEMAILメールワークスペースはじめるダウンロードドキュメント購入すべての製品
マーケットプレイス
ニュース
技術ニュース今日の開発ニュース開発ドキュメントプログラミング言語RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWebフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngularサーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Expressアプリ・デスクトップ フレームワークTauriFlutterReact NativeElectronアルゴリズムアルゴリズムの基礎主要アルゴリズム発展アルゴリズム実務のアルゴリズム
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケースコミュニティガイド
協業技術移転ウェブサイト構築デスクトップアプリ構築リリース・決済パイプライン販売パートナーお問い合わせ
サービスリモートデスクトップインストールパッケージのカスタマイズ
TASTEDEV
製品

デスクトップツール

TASTECAD複雑な図面を、軽やかにひらくTASTEFILES必要なファイルだけを、最速でTASTEFTPファイルが行き交う、いちばん端正な道TASTESSHサーバーとあなたを、より確かにつなぐTASTEZIPより速くまとめ、より安全にひらく

開発ツール

TASTECODERust アプリの編集・ビルド・デバッグ・テストまでひとつのウィンドウでTASTESTUDIO編集からリモートテスト、承認した AI 修正までTASTEETL値を見ながら、データを運ぶ

サーバー

TASTEREMOTE自社サーバーで運用するリモートデスクトップTASTEGEOGeoServer 互換の空間情報サーバーを Rust で作り直しますTASTEMAILメールの主導権を、もう一度自分の手に

はじめる

ダウンロード全製品の最新版ドキュメント各製品の使い方購入サブスクリプション・永久ライセンスすべての製品全製品を一覧で
すべての製品
マーケットプレイスニュース
技術

ニュース

今日の開発ニュース言語・フレームワーク・GitHub・AI の公式発表開発ドキュメント言語・フレームワーク・アルゴリズムのガイド

プログラミング言語

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

フレームワーク

Webフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngular
サーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
アプリ・デスクトップ フレームワークTauriFlutterReact NativeElectron

アルゴリズム

アルゴリズムの基礎計算量解析 · ソート · 探索 · 基本データ構造 · 木構造とヒープ主要アルゴリズムグラフ探索 · 最短経路と最小全域木 · 動的計画法 · 貪欲法 · 分割統治法 · バックトラッキング発展アルゴリズム文字列アルゴリズム · 数学と整数論 · ビット演算 · セグメント木 · Union-Find実務のアルゴリズムコーディング面接対策 · LRUキャッシュ · レート制限 · コンシステントハッシュ法
開発ドキュメントをすべて見る
コミュニティ
プロジェクトビルダーと作品を探す開発ログ決定と試行錯誤プロンプト再利用できる指示AIツールの問題Claude・Codex・Gemini の問題と回避策ショーケース完成した成果コミュニティガイドオープンにつくる方法
協業
技術移転Rust・egui でネイティブアプリを作るウェブサイト構築10言語、アカウント、ドキュメントとダウンロードデスクトップアプリ構築Rust・egui、WebView なしリリース・決済パイプライン署名・MSI・deb・rpm・AppImage・ハッシュ販売パートナー紹介して決済額の30%お問い合わせ構築・提携・投資のご相談
サービス
リモートデスクトップブラウザから自分のパソコンへインストールパッケージのカスタマイズ必要な機能だけ、設定は事前に
購入
JA
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
ログイン
ログイン
TASTEDEV

小さなツールから、より良い開発へ。

support@tastedev.netTASTEDEVを支援
製品製品ラインナップ購入ドキュメントダウンロードマーケットプレイスサポート
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケース
ポリシープライバシーポリシー利用規約サブスクリプション規約返金ポリシーコミュニティガイドライン
アカウントログイン新規登録
訪問者
今日
012345678901234567890123456789012345678901234567890123456789
昨日
012345678901234567890123456789012345678901234567890123456789
累計閲覧
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
商号
GXSOFT
代表者
CHOI YOUNG GU
事業者登録番号
853-44-00368
所在地
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
メール
whitecalvin@tastedev.net
個人情報保護責任者
CHOI YOUNG GU

© 2026 TASTEDEV製品情報は検証済みの開発ソースに基づいています。リリース・改善中

C# ドキュメント
C#
Getting Started with CSyntax BasicsTypes and DataProjects and PackagesErrors and TestingKey Concepts: LINQ, Delegates, and Async
ディスカッション

C# ガイド · 5/6

Errors and Testing

この章は現在、英語でのみ提供しています。

C# reports errors with exceptions. When one is thrown, execution unwinds up the call stack until a matching catch block handles it. This chapter covers handling exceptions, cleaning up with using, custom exception types, and unit testing with dotnet test.

try, catch, and finally

The first catch whose type matches wins, so list specific types before general ones. finally always runs, which makes it the place for cleanup.

try
{
    var text = File.ReadAllText("config.json");
    var port = int.Parse(text.Trim());
    Console.WriteLine($"Port: {port}");
}
catch (FileNotFoundException ex)
{
    Console.WriteLine($"Config file not found: {ex.FileName}");
}
catch (FormatException)
{
    Console.WriteLine("The port number is not a valid integer.");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
    Console.WriteLine($"Could not read the file: {ex.Message}");
}
finally
{
    Console.WriteLine("Finished reading configuration.");
}

The when clause is an exception filter: the handler runs only if the condition holds. To rethrow, use a bare throw; so the original stack trace survives; throw ex; restarts the trace and hides the real origin.

When failure is routine, as with user input, prefer the Try pattern: int.TryParse(input, out var value) just returns false.

Guard Clauses and Custom Exceptions

Fail fast on bad arguments using the built-in throw helpers. For domain errors, such as a broken business rule, derive your own type from Exception so callers can catch exactly that case.

public class InsufficientFundsException : Exception
{
    public InsufficientFundsException(decimal balance, decimal requested)
        : base($"Cannot withdraw {requested:F2} from a balance of {balance:F2}.")
    {
        Balance = balance;
        Requested = requested;
    }

    public decimal Balance { get; }
    public decimal Requested { get; }
}

public class Wallet(decimal balance)
{
    public decimal Balance { get; private set; } = balance;

    public void Withdraw(decimal amount, string reason)
    {
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
        ArgumentException.ThrowIfNullOrWhiteSpace(reason);

        if (amount > Balance)
            throw new InsufficientFundsException(Balance, amount);

        Balance -= amount;
    }
}

Exception class names end in Exception by convention. Wallet(decimal balance) is a primary constructor, whose parameter is visible across the class.

using and IDisposable

Files, sockets, and database connections implement ; releases what they hold, and guarantees that call even when an exception is thrown.

この章について質問がありますか?
前の章Projects and Packages次の章Key Concepts: LINQ, Delegates, and Async
IDisposable
Dispose
using
// using statement: disposed at the end of the block (the file is closed)
using (var writer = new StreamWriter("log.txt", append: true))
{
    writer.WriteLine($"{DateTime.Now:O} started");
}

// using declaration: disposed when the enclosing scope ends
using var reader = new StreamReader("log.txt");
Console.WriteLine(reader.ReadLine());

// your own types work with using once they implement IDisposable
using (new ElapsedTimer())
{
    Thread.Sleep(100);
}

sealed class ElapsedTimer : IDisposable
{
    private readonly System.Diagnostics.Stopwatch _watch = System.Diagnostics.Stopwatch.StartNew();
    public void Dispose() => Console.WriteLine($"Elapsed: {_watch.ElapsedMilliseconds} ms");
}

The compiler turns using into try/finally for you. For asynchronous cleanup (IAsyncDisposable), use await using.

Unit Testing with xUnit

The main .NET test frameworks are xUnit, NUnit, and MSTest. Assuming Wallet lives in a src/Wallet library, add an xUnit project like this:

dotnet new xunit -o tests/Wallet.Tests
dotnet sln add tests/Wallet.Tests
dotnet add tests/Wallet.Tests reference src/Wallet

dotnet test                                         # run every test
dotnet test --filter "FullyQualifiedName~Withdraw"  # run tests whose names match
using Xunit;

public class WalletTests
{
    [Fact]
    public void Withdraw_DecreasesBalance()
    {
        var wallet = new Wallet(100m);

        wallet.Withdraw(30m, "lunch");

        Assert.Equal(70m, wallet.Balance);
    }

    [Fact]
    public void Withdraw_MoreThanBalance_Throws()
    {
        var wallet = new Wallet(10m);

        var ex = Assert.Throws<InsufficientFundsException>(() => wallet.Withdraw(50m, "book"));
        Assert.Equal(50m, ex.Requested);
    }

    [Theory]
    [InlineData(0)]
    [InlineData(-100)]
    public void Withdraw_InvalidAmount_Throws(int amount)
    {
        var wallet = new Wallet(10m);
        Assert.Throws<ArgumentOutOfRangeException>(() => wallet.Withdraw(amount, "bad amount"));
    }
}

A [Fact] takes no inputs; a [Theory] runs once per [InlineData] row. Arrange, Act, Assert keeps each test easy to scan.

If You Prefer MSTest

MSTest, Microsoft's own framework, differs mainly in naming. Start with dotnet new mstest.

using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class WalletTests
{
    [TestMethod]
    public void Withdraw_DecreasesBalance()
    {
        var wallet = new Wallet(100m);
        wallet.Withdraw(30m, "lunch");
        Assert.AreEqual(70m, wallet.Balance);
    }
}
TaskxUnitMSTest
Test method[Fact][TestMethod]
Parameterized test[Theory] + [InlineData][TestMethod] + [DataRow]
Equality checkAssert.EqualAssert.AreEqual
Per-test setupconstructor[TestInitialize]

Summary

  • Use try/catch/finally, catch specific types first, and rethrow with throw;.
  • Use the Try pattern for routine failures and custom exceptions for domain errors.
  • Wrap IDisposable objects in using so cleanup always runs.
  • Create a test project with dotnet new xunit (or mstest) and run it with dotnet test.

コメント 0件

人気のコメント順新しい順

ログイン · ログインするとコメントできます。