.NET ヘルプ

C#におけるTry/Catch(開発者向けの仕組み)

更新済み 5月 16, 2023
共有:

C#でのプログラミングが初めての場合、「try catch」ステートメントという用語をよく耳にするかもしれません。 このチュートリアルでは、例外処理の世界に入り、catchブロックに焦点を当て、tryおよびcatch文を使用してコードをエラーに対してより強固にする方法を探ります。 道中、理解を深めるための実際の例をたくさん提供します。

例外とは何か、それを扱う理由とは何か?

C#では、例外はプログラムの実行中に発生し、命令の標準的な実行の進行を妨げる出来事を表します。 例外が発生すると、プログラムの流れが分岐し、例外が処理されない場合、プログラムは突然終了します。

例外処理は、このような混乱を引き起こすイベントを予測して管理する方法であり、プログラムが予期しない問題から回復し、意図した通りに実行を続けることができるようにします。 tryブロックとcatchブロックを使用することで、コードがエラーを優雅に処理し、ユーザーに有意義なフィードバックを提供することができます。

その try ブロック

tryブロックは、例外が発生する可能性があると予想されるコードセグメントです。 コードをtryブロックで囲むと、そのブロック内で発生する可能性のある例外を処理したいことをコンパイラに伝えることになります。

以下は、tryブロックの基本的な使用例です:


    try
    {
        // Code that may generate an exception
    }
    catch (Exception ex)
    {
        // handle the exception
    }

    try
    {
        // Code that may generate an exception
    }
    catch (Exception ex)
    {
        // handle the exception
    }
Try
		' Code that may generate an exception
	Catch ex As Exception
		' handle the exception
	End Try
VB   C#

キャッチブロックで例外をキャッチする

catchステートメントは、例外を処理するためにtryブロックと一緒に使用されます。 tryブロック内で例外が発生すると、プログラムの実行は適切なcatchブロックに飛び、そこで例外に対してプログラムがどのように応答するべきかを指定することができます。

例外をキャッチするには、tryブロックの直後にcatchブロックを作成する必要があります。 キャッチブロックには、通常、捕捉された例外を表すパラメータが含まれます。

以下は、キャッチステートメントの使用例です:


    try
    {
        int result = 10/0;
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine("An error occurred: " + ex.Message);
    }

    try
    {
        int result = 10/0;
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine("An error occurred: " + ex.Message);
    }
Try
		Dim result As Integer = 10\0
	Catch ex As DivideByZeroException
		Console.WriteLine("An error occurred: " & ex.Message)
	End Try
VB   C#

この例では、tryブロック内のコードがゼロでの除算を試み、その結果としてDivideByZeroExceptionが発生します。 キャッチブロックは次に例外を処理し、ユーザーにメッセージを表示します。

異なる例外を処理する複数のキャッチブロック

場合によっては、try ブロックでさまざまな種類の例外が発生することがあります。 そのような場合、複数のcatchブロックを使用して、各例外タイプを別々に処理することができます。

次の例は、複数のキャッチブロックの使用方法を示しています:


    try
    {
        int [] numbers = new int [7];
        numbers [12] = 70;
    }
    catch (IndexOutOfRangeException ex)
    {
        Console.WriteLine("An index out of range error occurred: " + ex.Message);
    }
    catch (Exception e)
    {
        Console.WriteLine("An unexpected error occurred: " + e.Message);
    }

    try
    {
        int [] numbers = new int [7];
        numbers [12] = 70;
    }
    catch (IndexOutOfRangeException ex)
    {
        Console.WriteLine("An index out of range error occurred: " + ex.Message);
    }
    catch (Exception e)
    {
        Console.WriteLine("An unexpected error occurred: " + e.Message);
    }
Try
		Dim numbers(6) As Integer
		numbers (12) = 70
	Catch ex As IndexOutOfRangeException
		Console.WriteLine("An index out of range error occurred: " & ex.Message)
	Catch e As Exception
		Console.WriteLine("An unexpected error occurred: " & e.Message)
	End Try
VB   C#

この例では、tryブロック内のコードが存在しない配列のインデックスに値を割り当てようとし、IndexOutOfRangeExceptionを生成します。 最初のcatchブロックはこの特定の例外を処理し、2番目のcatchブロックは他の発生する可能性のある例外をキャッチします。

複数のキャッチブロックを使用する場合、常に最も具体的な例外タイプから最も一般的な例外タイプへと順に並べてください。

例外フィルター キャッチブロックへの条件の追加

例外フィルタを使用すると、キャッチブロックに条件を追加でき、特定の条件が満たされた場合にのみ例外をキャッチできます。 例外フィルターを使用するには、catchステートメントに条件を続けてwhenキーワードを追加します。

次の例は、例外フィルタの使用を示しています。


    try
    {
        int result = 10 / 0;
    }
    catch (DivideByZeroException ex) when (ex.Message.Contains("divide"))
    {
        Console.WriteLine("An error occurred: " + ex.Message);
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine("A different divide by zero error occurred: " + ex.Message);
    }

    try
    {
        int result = 10 / 0;
    }
    catch (DivideByZeroException ex) when (ex.Message.Contains("divide"))
    {
        Console.WriteLine("An error occurred: " + ex.Message);
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine("A different divide by zero error occurred: " + ex.Message);
    }
Try
		Dim result As Integer = 10 \ 0
	Catch ex As DivideByZeroException When ex.Message.Contains("divide")
		Console.WriteLine("An error occurred: " & ex.Message)
	Catch ex As DivideByZeroException
		Console.WriteLine("A different divide by zero error occurred: " & ex.Message)
	End Try
VB   C#

上記の例では、最初のcatchブロックは、例外メッセージに「divide」という単語が含まれている場合にのみDivideByZeroExceptionを処理します。 条件が満たされない場合、第二のキャッチブロックが例外を処理します。

Finally ブロックはコードの実行を確実にします

場合によっては、例外が発生するかどうかにかかわらず、特定のコードが実行されるようにする必要があるかもしれません。 これを達成するためには、finallyブロックを使用することができます。

finally ブロックは、try ブロックと catch ブロックの後に配置され、例外が発生するかどうかに関係なく、常に実行されます。

finally ブロックの使用例は次のとおりです:


    try
    {
        int result = 10 / 2;
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine("An error occurred: " + ex.Message);
    }
    finally
    {
        Console.WriteLine("This line will always be executed.");
    }

    try
    {
        int result = 10 / 2;
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine("An error occurred: " + ex.Message);
    }
    finally
    {
        Console.WriteLine("This line will always be executed.");
    }
Try
		Dim result As Integer = 10 \ 2
	Catch ex As DivideByZeroException
		Console.WriteLine("An error occurred: " & ex.Message)
	Finally
		Console.WriteLine("This line will always be executed.")
	End Try
VB   C#

上記の例では、tryブロック内のコードが例外を発生させない場合でも、finallyブロックは実行されます。

カスタム例外: ニーズに合わせた例外のカスタマイズ

場合によっては、コード内の特定の例外を処理するために、独自のカスタム例外を作成したいことがあります。 これを行うには、Exceptionクラスを継承する新しいクラスを作成することができます。

以下はカスタム例外を作成する例です:


    public class CustomException : Exception
    {
        public CustomException(string errorMessage) : base(errorMessage)
        {
        }
    }

    public class CustomException : Exception
    {
        public CustomException(string errorMessage) : base(errorMessage)
        {
        }
    }
Public Class CustomException
	Inherits Exception

		Public Sub New(ByVal errorMessage As String)
			MyBase.New(errorMessage)
		End Sub
End Class
VB   C#

今、このカスタム例外をtryブロックおよびcatchブロックで次のように使用できます:


    try
    {
        throw new CustomException("This is a custom exception.");
    }
    catch (CustomException ex)
    {
        Console.WriteLine("A custom exception occurred: " + ex.Message);
    }

    try
    {
        throw new CustomException("This is a custom exception.");
    }
    catch (CustomException ex)
    {
        Console.WriteLine("A custom exception occurred: " + ex.Message);
    }
Try
		Throw New CustomException("This is a custom exception.")
	Catch ex As CustomException
		Console.WriteLine("A custom exception occurred: " & ex.Message)
	End Try
VB   C#

この例では、tryブロックがCustomExceptionインスタンスをスローし、catchブロックによって捕捉され処理されます。

IronPDF:例外処理を伴うPDF機能の統合

IronPDF は、C#でPDFファイルの作成、編集、およびコンテンツの抽出に人気のあるライブラリです。 このセクションでは、潜在的なエラーを優雅に処理するために、IronPDFをtry-catch例外処理アプローチと統合する方法を探ります。

IronPDFのインストール

始めるには、まずIronPDF NuGetパッケージをインストールする必要があります。 以下のコマンドを使用してパッケージマネージャーコンソールで実行できます:

Install-Package IronPdf

または、Visual Studioの「NuGetパッケージの管理」ダイアログで「IronPDF」を検索することもできます。

IronPDFを使用してPDFを作成し、例外を処理する

以下のコンテンツを日本語に翻訳してください:

たとえば、あなたが HTMLからPDFファイルを作成する IronPDFを使用する文字列。 PDFの作成プロセスは例外を発生させる可能性があるため、それらを処理するために try-catch ブロックを使用できます。 以下は、IronPDFを使用してPDFを作成し、try-catchを使用して例外を処理する方法の例です:


    using IronPdf;
    using System;
    try
    {
        var renderer = new IronPDF.ChromePdfRenderer();
        string html = "Hello, World!";
        PdfDocument PDF = renderer.RenderHtmlAsPdf(html);
        PDF.SaveAs("output.PDF");
        Console.WriteLine("PDF created successfully.");
    }
    catch (Exception ex)
    {
        Console.WriteLine("An unexpected error occurred: " + ex.Message);
    }

    using IronPdf;
    using System;
    try
    {
        var renderer = new IronPDF.ChromePdfRenderer();
        string html = "Hello, World!";
        PdfDocument PDF = renderer.RenderHtmlAsPdf(html);
        PDF.SaveAs("output.PDF");
        Console.WriteLine("PDF created successfully.");
    }
    catch (Exception ex)
    {
        Console.WriteLine("An unexpected error occurred: " + ex.Message);
    }
Imports IronPdf
	Imports System
	Try
		Dim renderer = New IronPDF.ChromePdfRenderer()
		Dim html As String = "Hello, World!"
		Dim PDF As PdfDocument = renderer.RenderHtmlAsPdf(html)
		PDF.SaveAs("output.PDF")
		Console.WriteLine("PDF created successfully.")
	Catch ex As Exception
		Console.WriteLine("An unexpected error occurred: " & ex.Message)
	End Try
VB   C#

この例では、tryブロックにIronPDFを使用してPDFを作成するコードが含まれています。 処理中に例外が発生した場合、catchブロックがエラーを処理し、ユーザーに適切なエラーメッセージを表示します。

PDFからのテキスト抽出と例外処理

IronPDFを使用してPDFファイルからテキストを抽出することもできます。 前の例と同様に、潜在的な例外を処理するために try-catch ブロックを使用できます。

PDFファイルからテキストを抽出し、例外を処理する例を以下に示します(IronPDFを使用):


    using IronPdf;
    using System;
    using System.IO;

    try
    {
        string pdfPath = "input.PDF";
        if (File.Exists(pdfPath))
        {
            PdfDocument PDF = PdfDocument.FromFile(pdfPath);
            string extractedText = PDF.ExtractAllText();
            Console.WriteLine("Text extracted successfully: " + extractedText);
        }
        else
        {
            Console.WriteLine("The specified PDF file does not exist.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("An unexpected error occurred: " + ex.Message);
    }

    using IronPdf;
    using System;
    using System.IO;

    try
    {
        string pdfPath = "input.PDF";
        if (File.Exists(pdfPath))
        {
            PdfDocument PDF = PdfDocument.FromFile(pdfPath);
            string extractedText = PDF.ExtractAllText();
            Console.WriteLine("Text extracted successfully: " + extractedText);
        }
        else
        {
            Console.WriteLine("The specified PDF file does not exist.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("An unexpected error occurred: " + ex.Message);
    }
Imports IronPdf
	Imports System
	Imports System.IO

	Try
		Dim pdfPath As String = "input.PDF"
		If File.Exists(pdfPath) Then
			Dim PDF As PdfDocument = PdfDocument.FromFile(pdfPath)
			Dim extractedText As String = PDF.ExtractAllText()
			Console.WriteLine("Text extracted successfully: " & extractedText)
		Else
			Console.WriteLine("The specified PDF file does not exist.")
		End If
	Catch ex As Exception
		Console.WriteLine("An unexpected error occurred: " & ex.Message)
	End Try
VB   C#

C# における Try/Catch(開発者向けの仕組み)図1

この例では、tryブロックにIronPDFを使用してPDFからテキストを抽出するコードが含まれています。 処理中に例外が発生した場合、catchブロックがエラーを処理し、関連するメッセージをユーザーに表示します。

結論

組み合わせることによって IronPDF あなたのtry-catch例外処理アプローチを使用すると、PDFファイルを取り扱う際にエラーを優雅に処理する堅牢なアプリケーションを作成することができます。 これにより、アプリケーションの安定性が向上するだけでなく、全体的なユーザー体験も改善されます。

外部ライブラリであるIronPDFを使用する際は、常に潜在的な例外を考慮し、try及びcatch文を使用して適切に処理することを忘れないでください。 この方法により、予期しない問題に対処する際でも、アプリケーションが堅牢でユーザーフレンドリーであることを保証できます。

IronPDFは 無料試用、その機能を拘束なしに探索することができます。 試用期間終了後もIronPDFの使用を続ける場合、ライセンスは$liteLicenseから開始します。

< 以前
C# For Each(開発者向けの仕組み)
次へ >
C#拡張メソッド(開発者向けの使用方法)

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

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