Using vs. Try-Finally
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 28/66。
using ステートメントと try-finally ブロックの両方は、適切に破棄する必要があるリソースを管理するのに役立ちます。using ステートメントは、IDisposable オブジェクトが適切にクリーンアップされることを保証するための、よりクリーンで簡潔な方法を提供します。
まず try-finally アプローチを見てみましょう。ここで、StreamReader はファイルからテキストを読み取るクラスです — それはオープンされたファイルハンドルを持ち、使用後に解放しなければならないリソースです:
StreamReader reader = null;
try
{
reader = new StreamReader("file.txt");
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
finally
{
if (reader != null)
{
reader.Dispose();
}
}
finally ブロックは、try ブロック内で例外が発生した場合でも、ファイルハンドルを解放するために Dispose() が呼び出されることを保証します。
using ステートメントはこのパターンを簡略化します。括弧内でリソースを宣言・初期化し、ブロックが終了する際(正常終了時または例外発生時いずれの場合も)に自動的に Dispose() を呼び出します:
using (StreamReader reader = new StreamReader("file.txt"))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
これは上記の try-finally の例と同等ですが、ボイラープレートコードが少なくなっています。
using ステートメントは、ブロックが終了する際に、例外が発生した場合でも自動的に Dispose() を呼び出します。これは try-finally クリーンアップ パターンを置き換えます — ではありません try-catch。例外を処理する必要がある場合は、using ブロックを try-catch 内にラップすることもできます。
チャレンジ
簡単processFile という名前のメソッドを作成してください。それには:
- ファイル名を文字列パラメータとして受け取る
StreamReaderを使用したusing文でファイルからすべての行を読み取る- ファイル内の行数を返す
FileNotFoundExceptionが発生した場合、"File not found" を出力し -1 を返す
チートシート
using 文は、IDisposable オブジェクトに対して自動的なリソースクリーンアップを提供し、例外が発生した場合でも Dispose() が呼び出されることを保証します。これにより、冗長な try-finally パターンを置き換えます。
Try-finally アプローチ:
StreamReader reader = null;
try
{
reader = new StreamReader("file.txt");
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
finally
{
if (reader != null)
{
reader.Dispose();
}
}
Using 文(よりクリーンなアプローチ):
using (StreamReader reader = new StreamReader("file.txt"))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
両方のアプローチは、ブロックが終了するときに Dispose() が呼び出されることを保証します。using 文はこれを自動的に処理し、手動の null チェックと finally ブロックの必要性を排除します。
主なポイント:
• using は try-finally を置き換えます — try-catch ではありません
• 例外の処理のために try-catch を using と組み合わせることができます
• StreamReader はテキストファイルを読込み、IDisposable を実装しており、using との使用に最適です
自分で試してみよう
using System;
using System.IO;
class ProcessFile
{
public static int processFile(string filename)
{
// ここにコードを記述してください
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety