フッターコンテンツにスキップ
.NETヘルプ

C# Catch Multiple Exceptions(開発者向けの動作方法)

例外処理を適切に行うことはC#で不可欠です。 このチュートリアルでは、複数のキャッチ句を持つtry-catchブロックの使用方法を紹介します。 複数の例外タイプをキャッチする方法、例外フィルターを使用する方法、および最終処理でリソースをクリーンアップする方法をカバーします。 目標は、堅牢でエラートレラントなC#アプリケーションを構築する手助けをすることです。

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

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

例外処理とは何ですか?

C#における例外処理は、ランタイムエラーを処理し、プログラムの突然の終了を防ぎ、プログラム実行中に発生する予期しない状況を管理するために使用される方法です。 例外処理のコアコンポーネントには、trycatchfinallyブロックがあります。

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
$vbLabelText   $csharpLabel

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

実際のアプリケーションでは、単一の操作がさまざまな種類の例外をスローする可能性があります。これに対応するため、C#では単一の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
$vbLabelText   $csharpLabel

このコードでは、IndexOutOfRangeExceptionDivideByZeroExceptionのような特定の例外が、それぞれのcatchブロックによってキャッチされます。 その他のタイプの例外は、ジェネリックなExceptionキャッチブロックによってキャッチされます。

Whenキーワードを使った例外フィルターの使用

C#はまた、キャッチブロック内で条件を指定できる例外フィルターをサポートしています。 この機能は、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
$vbLabelText   $csharpLabel

Finallyブロックの役割

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

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
$vbLabelText   $csharpLabel

IronPDFの紹介

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

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

インターリンク:

IronPDFの重要な機能はHTMLをPDFに変換することで、レイアウトとスタイルの両方を保持します。 これは、レポート、請求書、ドキュメントのためにWebコンテンツからPDFを生成するのに最適です。 HTMLファイル、URL、HTML文字列はすべてPDFファイルに変換可能です。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

コード例

これは、HTMLからPDFを作成するためにIronPDFを使用するシンプルなC#の例で、複数の種類の例外を処理するエラー処理があります。 この例では、プロジェクトにIronPDFをインストールしていることを前提としています。 NuGetコンソールでこのコマンドを実行してIronPDFをインストールします:

Install-Package IronPdf

こちらがコードです:

using IronPdf;
using System;

class Program
{
    static void Main(string[] args)
    {
        // Set your IronPDF license key, if applicable.
        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)
    {
        // Set your IronPDF license key, if applicable.
        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)
		' Set your IronPDF license key, if applicable.
		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
$vbLabelText   $csharpLabel

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

C# 複数の例外をキャッチする (開発者のための説明): 図1

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

C# 複数の例外をキャッチする (開発者のための説明): 図2

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

結論

C# 複数の例外をキャッチする (開発者のための説明): 図3

C#での複数の例外の処理は、アプリケーション内で強力なエラーハンドリング機能を提供する強力な機能です。 複数のcatchブロック、例外フィルター、およびfinallyブロックを使用すると、さまざまなエラーを上手に処理し、アプリケーションが異なるエラー状況でもその完全性を維持するための回復力と安定性を持つアプリケーションを作成できます。

この包括的な例外処理の理解と実装により、アプリケーションは予期しない状況に効果的に対処する準備が整います。 IronPDFは$799から始める無料トライアルを提供しています。

よくある質問

C#で例外を処理するための高度な技術には何がありますか?

C#で例外を処理するための高度な技術には、異なる例外タイプを処理するために複数のcatchブロックを使用し、whenキーワードを使用して例外フィルターを適用し、リソースのクリーンアップを確保するためのfinallyブロックを利用することが含まれます。これらの技術は堅牢でエラー耐性のあるアプリケーションを構築するのに役立ちます。

C#アプリケーションで複数の例外をどのように処理できますか?

C#アプリケーションで複数の例外を処理するには、複数のcatchブロックを使用します。各catchブロックは特定のタイプの例外を処理するように設計されており、さまざまなエラーシナリオに対するカスタマイズされた応答を可能にします。

例外フィルターとは何ですか?それらはどのように機能しますか?

例外フィルターは、whenキーワードを使用してcatchブロックで指定された条件です。開発者が特定の実行時条件に基づいて例外を捕捉することを可能にし、より正確なエラー処理の制御を提供します。

PDF生成の例外処理にIronPDFはどのように役立ちますか?

IronPDFはC#プロジェクトに統合され、PDF生成を補助し、try-catchブロックを使用してPDF作成プロセス中に発生する可能性のあるエラーを管理することができます。この統合はアプリケーション内でのエラー耐性操作を保証するのに役立ちます。

C#でfinallyブロックを使用してリソースを管理することはなぜ重要なのですか?

finallyブロックは、ファイルストリームやデータベース接続などのリソースを管理するために重要です。これは例外が投げられたかどうかにかかわらず、tryブロックとcatchブロックの後にコードを実行します。それにより、リソースが適切に解放されてクリーンアップされることが保証されます。

C#ライブラリを使用して、サードパーティーアプリケーションに頼らずにPDFを生成できますか?

はい、IronPDFのようなライブラリを使用することで、Adobe Acrobatのようなサードパーティーアプリケーションを必要とせずに、C#アプリケーション内で直接PDFを生成できます。これらのライブラリは、PDFドキュメントの変換、編集、管理の機能を提供します。

エラー処理で複数のcatchブロックを使用することの重要性は何ですか?

エラー処理で複数のcatchブロックを使用することは、開発者が異なる種類の例外に特有の対応をすることを可能にし、エラー応答の特異性と有効性を向上し、さまざまなエラー条件に対するアプリケーションの耐性を向上させます。

C#プロジェクトの信頼性を向上させるために開発者ができることは何ですか?

開発者は、複数のcatchブロック、例外フィルター、およびfinallyブロックを使用するなど、包括的な例外処理戦略を実装することで、C#プロジェクトの信頼性を向上させることができます。特にPDF生成のような複雑なタスクに取り組む際にこれを行うべきです。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。