Using vs. Try-Finally
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 28번째.
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