Using vs. Try-Finally
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 28번째.
using 문과 try-finally 블록은 모두 적절하게 해제되어야 하는 리소스를 관리하는 데 도움이 됩니다. using 문은 IDisposable 객체가 적절하게 정리되도록 보장하는 더 깔끔하고 간결한 방법을 제공합니다.
참고: using은 폐기를 위한 try-finally 패턴을 대체합니다. 이는 try-catch를 대체하는 것이 아닙니다. 예외를 처리하기 위해 여전히 try-catch 내부에 using 블록을 래핑할 수 있습니다.
먼저 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);
}
using 문은 예외가 발생하더라도 블록이 종료될 때 자동으로 Dispose()를 호출합니다.
StreamReader란 무엇인가요?StreamReader는 파일에서 텍스트를 읽는 데 사용되는 클래스입니다. 파일 이름을 전달하여 생성하면, 읽기 위해 파일을 엽니다. 이 클래스는 IDisposable을 구현하므로 사용 후에는 적절히 닫아야 합니다. 이것이 바로 using이 대신 처리해 주는 작업입니다.
일반적인 StreamReader 메서드:
ReadToEnd()— 파일 전체를 하나의 문자열로 읽습니다ReadLine()— 한 번에 한 줄씩 읽으며, 파일의 끝에 도달하면null을 반환합니다
파일의 줄 수를 세려면 ReadLine() 루프를 사용할 수 있습니다:
using (StreamReader reader = new StreamReader("file.txt"))
{
int lineCount = 0;
while (reader.ReadLine() != null)
{
lineCount++;
}
Console.WriteLine(lineCount);
}
또한 using을 try-catch와 결합하여 파일 누락과 같은 예외를 처리할 수도 있습니다:
try
{
using (StreamReader reader = new StreamReader("file.txt"))
{
int lineCount = 0;
while (reader.ReadLine() != null)
{
lineCount++;
}
Console.WriteLine(lineCount);
}
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found");
}
챌린지
쉬움다음과 같은 기능을 수행하는 processFile 메서드를 작성하세요:
- 파일 이름을 문자열 매개변수로 받습니다.
StreamReader와 함께using문을 사용하여 파일의 모든 줄을 읽습니다.- 파일의 총 줄 수를 반환합니다.
FileNotFoundException이 발생하면, "File not found"를 출력하고 -1을 반환합니다.
직접 해보기
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