C# の Try/Catch (開発者向けの仕組み)
C#プログラミングに慣れていない場合は、"try 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 ex As Exception
' Handle the exception
End TryTry
' Code that may generate an exception
Catch ex As Exception
' Handle the exception
End Try捕捉する例外をキャッチするブロック
catchステートメントは、例外を処理するためにtryブロックと共に使用されます。 tryブロック内で例外が発生すると、プログラムの実行は適切なcatchブロックにジャンプし、例外に対するプログラムの対応を指定することができます。
例外を捕捉するには、tryブロックの直後にcatchブロックを作成する必要があります。 catchブロックには通常、捕捉された例外を表すパラメータが含まれます。
アクション中の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 TryTry
Dim result As Integer = 10 \ 0
Catch ex As DivideByZeroException
Console.WriteLine("An error occurred: " & ex.Message)
End Tryこの例では、tryブロック内のコードが0で割ろうとするため、DivideByZeroExceptionを生成します。 その後、catchブロックが例外を処理し、ユーザーにメッセージを表示します。
異なる例外を処理する複数のキャッチブロック
場合によっては、tryブロックで異なるタイプの可能性のある例外が発生することがあります。 そのような場合、複数のcatchブロックを使用して、各例外タイプを個別に処理できます。
複数のcatchブロックの使用方法を示す例を以下に示します。
try
{
int[] numbers = new int[7];
numbers[12] = 70; // This line will throw an exception
}
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; // This line will throw an exception
}
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 ' This line will throw an exception
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 TryTry
Dim numbers(6) As Integer
numbers(12) = 70 ' This line will throw an exception
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この例では、tryブロック内のコードが存在しない配列インデックスに値を割り当てようとしてIndexOutOfRangeExceptionを生成します。 最初のcatchブロックがこの特定の例外を処理し、二番目のcatchブロックが発生する可能性のある他の例外を捕捉します。
複数のcatchブロックを使用する場合、常に最も特定の例外タイプから最も一般的なものへ順序を付けてください。
キャッチブロックに条件を追加する例外フィルター
例外フィルターを使用すると、特定の条件が満たされた場合のみ例外を捕捉するための条件をキャッチブロックに追加できます。 例外フィルターを使用するには、whenキーワードを追加し、catch文に条件を続けます。
例外フィルターの使用を示す例を以下に示します。
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 TryTry
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上記の例では、例外メッセージに"divide"という単語が含まれている場合にのみ、最初のcatchブロックが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 TryTry
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上記の例では、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 ClassPublic Class CustomException
Inherits Exception
Public Sub New(ByVal errorMessage As String)
MyBase.New(errorMessage)
End Sub
End Class今度は、このカスタム例外を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 TryTry
Throw New CustomException("This is a custom exception.")
Catch ex As CustomException
Console.WriteLine("A custom exception occurred: " & ex.Message)
End Tryこの例では、tryブロックがCustomExceptionインスタンスを投げ、それがcatchブロックで捕捉され処理されます。
IronPDF:例外処理とPDF機能の統合
IronPDFについてさらに学ぶは、C#でPDFファイルを作成、編集、およびコンテンツを抽出するための人気のあるライブラリです。 このセクションでは、IronPDFを例外処理のtry-catchアプローチに統合し、潜在的なエラーを優雅に処理する方法を探ります。
IronPDFのインストール
始めるには、まずIronPDFのNuGetパッケージをインストールする必要があります。 パッケージマネージャーコンソールを使用してこれを行うことができます。
または、Visual Studioの"NuGetパッケージの管理"ダイアログで"IronPDF"を検索することもできます。
IronPDFでPDFを作成し、例外を処理する
HTML文字列からIronPDFを使用してPDFファイルを作成したいとしましょう。 PDFの作成過程で例外が発生する可能性があるため、try-catchブロックを使用してそれらを処理することができます。 IronPDFを使用してPDFを作成し、try-catchで例外を処理する方法の例を示します:
using IronPdf;
using System;
try
{
var renderer = new 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 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 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 TryImports IronPdf
Imports System
Try
Dim renderer = New 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この例では、tryブロックにIronPDFを使用してPDFを作成するコードが含まれています。 処理中に例外が発生した場合、catchブロックがエラーを処理し、ユーザーに関連するエラーメッセージを表示します。
PDFからテキストを抽出し、例外を処理する
また、IronPDFを使用してPDFファイルからテキストを抽出したいかもしれません。 前の例と同様に、try-catchブロックを使用して潜在的な例外を処理することができます。
IronPDFを使用してPDFファイルからテキストを抽出し、例外を処理する例を次に示します。
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 TryImports 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 TryTry/Catch in C# (開発者向けの仕組み) 図1
この例では、tryブロックにIronPDFを使用してPDFからテキストを抽出するコードが含まれています。 処理中に例外が発生した場合、catchブロックがエラーを処理し、ユーザーに関連するメッセージを表示します。
結論
IronPDFを例外処理のtry-catchアプローチと組み合わせることで、PDFファイルを操作する際にエラーを優雅に処理する堅牢なアプリケーションを作成することができます。 これによりアプリケーションの安定性が向上するだけでなく、全体的なユーザーエクスペリエンスも向上します。
外部ライブラリのIronPDFを使用する際には、常に潜在的な例外を考慮し、tryおよびcatchステートメントを適切に使用して処理してください。 このようにして、アプリケーションが予期しない問題にも堅牢でユーザーフレンドリーであることを保証できます。
IronPDFはライブラリの無料トライアルを提供しており、コミットなしにその機能を探索できます。 トライアル期間後もIronPDFを使用し続ける場合、ライセンスは$999から始まります。
ジェイコブ・メラーはIron Softwareの最高技術責任者(CTO)であり、C# PDFテクノロジーを開拓する先見的なエンジニアです。Iron Softwareのコアコードベースを支えるオリジナル開発者として、彼は創業以来、会社の製品アーキテクチャを形成し、CEOのCameron Rimingtonとともに、会社をNASA、Tesla、および世界的な政府機関にサービスを提供する50人以上の会社に変えました。1999年にロンドンで最初のソフトウェアビジネスを開業し、2005年に最初 for .NETコンポーネントを作成した後、Microsoftのエコシステム全体で複雑な問題を解決することを専門としました。