.NET ヘルプ

C# 複数例外のキャッチ(開発者向けの仕組み)

更新済み 6月 6, 2024
共有:

例外処理 C#で適切に このチュートリアルでは、複数のcatch句を持つtry-catchブロックの使用方法を紹介します。 複数の例外タイプをキャッチする方法、例外フィルターの使用、およびリソースが必ずクリーンアップされるようにするための最終処理について説明します。 目標は、堅牢でエラー耐性のあるC#アプリケーションを構築するのに役立つことです。

複数のタイプの例外をキャッチする方法を学ぶことで、特定の問題に対する応答を調整し、プログラムの信頼性を向上させることができます。 when キーワードを使用してキャッチブロックに条件を適用する方法についても触れ、より正確なエラーハンドリングを可能にします。

このガイドでは、例外をキャッチし、一般的なエラーや複雑なエラーをスムーズに処理する方法を提供します。 また、以下を探ります IronPDF 例外処理の文脈において。

例外処理とは何ですか?

C#における例外処理は、実行時のエラーを処理し、プログラムの突然の終了を防止し、プログラムの実行中に発生する予期しない状況を管理するための方法です。 例外処理のコアコンポーネントには、tryブロック、catchブロック、そしてfinallyブロックが含まれます。

C#におけるTry-Catchの基本構造

try ブロックには例外を発生させる可能性のあるコードが含まれており、catch ブロックは例外が発生した場合にそれを処理します。 finally ブロックはオプションであり、例外が投げられたかどうかに関わらず、try ブロックと catch ブロックの後にコードを実行します。 以下はシンプルな構造です:

try {
    // Code that may throw an exception
}
catch (Exception e) {
    // Code to handle the exception
}
finally {
    // Code that executes after try and catch, regardless of an exception
}
try {
    // Code that may throw an exception
}
catch (Exception e) {
    // Code to handle the exception
}
finally {
    // Code that executes after try and catch, regardless of an exception
}
Try
	' Code that may throw an exception
Catch e As Exception
	' Code to handle the exception
Finally
	' Code that executes after try and catch, regardless of an exception
End Try
VB   C#

複数の例外をキャッチする

実際のアプリケーションでは、単一の操作がさまざまな種類の例外をスローすることがあります。これに対処するために、C#では1つのtryブロックに対して複数のcatchブロックを定義することができます。 各キャッチブロックは、すべての例外を処理するために異なる例外タイプを指定することができます。

なぜ複数の例外をキャッチするのか?

複数の例外を捕捉することは詳細なエラー処理にとって不可欠であり、発生した具体的なエラーに応じてアクションが決定されます。 それにより、開発者は特定のエラーの文脈に適した方法で各例外を処理することができます。

複数のキャッチブロックを実装する方法

複数の例外型をキャッチするための単一のキャッチブロックを実装する例を以下に示します:

try {
    // Code that may throw multiple types of exceptions
    int[] numbers = {1, 2, 3};
    Console.WriteLine(numbers[5]); // This will throw an IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex) {
    Console.WriteLine("An index was out of range: " + ex.Message);
}
catch (DivideByZeroException ex) {
    Console.WriteLine("Can't divide by Zero: " + ex.Message);
}
catch (Exception ex) {
    Console.WriteLine("Error: " + ex.Message);
}
try {
    // Code that may throw multiple types of exceptions
    int[] numbers = {1, 2, 3};
    Console.WriteLine(numbers[5]); // This will throw an IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex) {
    Console.WriteLine("An index was out of range: " + ex.Message);
}
catch (DivideByZeroException ex) {
    Console.WriteLine("Can't divide by Zero: " + ex.Message);
}
catch (Exception ex) {
    Console.WriteLine("Error: " + ex.Message);
}
Try
	' Code that may throw multiple types of exceptions
	Dim numbers() As Integer = {1, 2, 3}
	Console.WriteLine(numbers(5)) ' This will throw an IndexOutOfRangeException
Catch ex As IndexOutOfRangeException
	Console.WriteLine("An index was out of range: " & ex.Message)
Catch ex As DivideByZeroException
	Console.WriteLine("Can't divide by Zero: " & ex.Message)
Catch ex As Exception
	Console.WriteLine("Error: " & ex.Message)
End Try
VB   C#

このコードでは、IndexOutOfRangeExceptionDivideByZeroException のような特定の例外がそれぞれの catch ブロックによって捕捉されます。 他の種類の例外はすべて、汎用的な Exception キャッチブロックによって捕捉されます。

When キーワードを使用した例外フィルタリング

C# は、catch ブロック内で条件を指定できる例外フィルターもサポートしています。 この機能は、実行時に評価される条件に基づいてどの例外をキャッチするかをより制御するために when キーワードを使用します。

以下は、when キーワードを使用して例外フィルターを追加する方法です:

try {
    // Code that may throw an exception
    throw new InvalidOperationException("Invalid operation occurred", new Exception("Inner exception"));
}
catch (Exception ex) when (ex.InnerException != null) {
    Console.WriteLine("Exception with inner exception caught: " + ex.Message);
}
catch (Exception ex) {
    Console.WriteLine("Exception caught: " + ex.Message);
}
try {
    // Code that may throw an exception
    throw new InvalidOperationException("Invalid operation occurred", new Exception("Inner exception"));
}
catch (Exception ex) when (ex.InnerException != null) {
    Console.WriteLine("Exception with inner exception caught: " + ex.Message);
}
catch (Exception ex) {
    Console.WriteLine("Exception caught: " + ex.Message);
}
Try
	' Code that may throw an exception
	Throw New InvalidOperationException("Invalid operation occurred", New Exception("Inner exception"))
Catch ex As Exception When ex.InnerException IsNot Nothing
	Console.WriteLine("Exception with inner exception caught: " & ex.Message)
Catch ex As Exception
	Console.WriteLine("Exception caught: " & ex.Message)
End Try
VB   C#

Finally ブロックの役割

finally ブロックは、try および任意の catch ブロックが完了した後にコードを実行するために使用されます。 例外が発生したかどうかに関わらず、ファイルストリームやデータベース接続などのリソースを解放するために役立ちます。

try {
    // Code that might throw an exception
}
catch (Exception e) {
    // Handle the exception
}
finally {
    // Cleanup code, executed after try/catch
    Console.WriteLine("Cleanup code runs here.");
}
try {
    // Code that might throw an exception
}
catch (Exception e) {
    // Handle the exception
}
finally {
    // Cleanup code, executed after try/catch
    Console.WriteLine("Cleanup code runs here.");
}
Try
	' Code that might throw an exception
Catch e As Exception
	' Handle the exception
Finally
	' Cleanup code, executed after try/catch
	Console.WriteLine("Cleanup code runs here.")
End Try
VB   C#

IronPDFの紹介

IronPDF は.NETアプリケーションで作業するC#開発者向けに設計された包括的なライブラリです。 開発者が操作および管理するのを支援し、 HTMLから直接PDFファイルを作成します. 外部依存関係を必要としません。

Adobe Acrobatを使用およびインストールすることなく、任意のPDF操作を行うことができます。 IronPDFは、PDF文書の編集、結合、分割、暗号化やデジタル署名によるセキュリティ強化など、さまざまなPDF機能をサポートしています。 開発者は、Webアプリケーション、デスクトップアプリケーション、サービスなど、さまざまなアプリケーションタイプでIronPDFを利用できます。

コード例

以下に、IronPDFを使用してHTMLからPDFを作成し、複数種類の例外に対するエラーハンドリングを行う簡単なC#の例を示します。 この例は、プロジェクトにIronPDFがインストールされていることを前提としています。 このコマンドをNuGetコンソールで実行してIronPDFをインストールしてください:

Install-Package IronPdf

こちらがコードです:

using IronPdf;
using System;
class Program
{
    static void Main(string[] args)
    {
        License.LicenseKey = "License-Key";
        var renderer = new ChromePdfRenderer();
        try
        {
            // Convert HTML to PDF
            var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
            pdf.SaveAs("Exceptions.pdf");
            Console.WriteLine("PDF successfully created.");
        }
        catch (IronPdf.Exceptions.IronPdfProductException ex)
        {
            // Handle PDF generation errors
            Console.WriteLine("Failed to generate PDF: " + ex.Message);
        }
        catch (System.IO.IOException ex)
        {
            // Handle IO errors (e.g., disk I/O errors)
            Console.WriteLine("IO Exception: " + ex.Message);
        }
        catch (Exception ex)
        {
            // Handle other errors
            Console.WriteLine("Error" + ex.Message);
        }
    }
}
using IronPdf;
using System;
class Program
{
    static void Main(string[] args)
    {
        License.LicenseKey = "License-Key";
        var renderer = new ChromePdfRenderer();
        try
        {
            // Convert HTML to PDF
            var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
            pdf.SaveAs("Exceptions.pdf");
            Console.WriteLine("PDF successfully created.");
        }
        catch (IronPdf.Exceptions.IronPdfProductException ex)
        {
            // Handle PDF generation errors
            Console.WriteLine("Failed to generate PDF: " + ex.Message);
        }
        catch (System.IO.IOException ex)
        {
            // Handle IO errors (e.g., disk I/O errors)
            Console.WriteLine("IO Exception: " + ex.Message);
        }
        catch (Exception ex)
        {
            // Handle other errors
            Console.WriteLine("Error" + ex.Message);
        }
    }
}
Imports IronPdf
Imports System
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		License.LicenseKey = "License-Key"
		Dim renderer = New ChromePdfRenderer()
		Try
			' Convert HTML to PDF
			Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>")
			pdf.SaveAs("Exceptions.pdf")
			Console.WriteLine("PDF successfully created.")
		Catch ex As IronPdf.Exceptions.IronPdfProductException
			' Handle PDF generation errors
			Console.WriteLine("Failed to generate PDF: " & ex.Message)
		Catch ex As System.IO.IOException
			' Handle IO errors (e.g., disk I/O errors)
			Console.WriteLine("IO Exception: " & ex.Message)
		Catch ex As Exception
			' Handle other errors
			Console.WriteLine("Error" & ex.Message)
		End Try
	End Sub
End Class
VB   C#

このコードを実行すると、コマンドラインにこのメッセージが表示されます。

C# で複数の例外をキャッチする方法(開発者向けの仕組み):図1

そして、これはこのコードによって生成されたPDFファイルです:

C# 複数の例外をキャッチする(開発者向けの操作方法):図2

IronPDFが適切に構成されている環境でこれをテストし、アプリケーションに必要なHTMLコンテンツを修正してください。 これはエラーを効率的に管理するのに役立ち、PDF生成タスクの信頼性を向上させます。

結論

C# 複数の例外をキャッチする方法 (開発者向けの機能解説): 図3

C#で複数の例外を処理することは、アプリケーションにおいて強力なエラーハンドリング機能を提供する優れた機能です。 複数の catch ブロック、例外フィルター、および finally ブロックを使用することで、異なるエラーを優雅に処理し、さまざまなエラー条件下でもその完全性を維持する、堅牢で安定したアプリケーションを作成することができます。

この包括的な理解と複数の例外処理の実装により、アプリケーションが予期しない状況に効果的に対処できるようにしっかりと準備されます。 IronPDFは 無料試用 $749から開始します。

< 以前
WebClient C#(開発者向けの動作方法)
次へ >
C# ラムダ式(開発者向けの動作説明)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >