Finally Block
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 27번째.
finally 블록은 예외가 발생하든 발생하지 않든, try 또는 catch 블록에 return 문이 있더라도 항상 실행되는 코드를 포함합니다.
기본적인 try-catch-finally 구조를 생성하세요:
try
{
// Code that might throw an exception
int result = 10 / 2;
Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
// Code that handles the exception
Console.WriteLine("Cannot divide by zero: " + ex.Message);
}
finally
{
// Code that always executes
Console.WriteLine("This always executes");
}
finally 블록은 파일이나 데이터베이스 연결을 닫는 등의 정리 작업에 유용합니다:
System.IO.StreamReader file = null;
try
{
file = new System.IO.StreamReader("data.txt");
string content = file.ReadToEnd();
Console.WriteLine(content);
}
catch (System.IO.FileNotFoundException)
{
Console.WriteLine("File not found.");
}
finally
{
// Always close the file, even if an exception occurred
if (file != null)
{
file.Close();
}
}
챌린지
쉬움ProcessData라는 메서드를 생성하세요. 다음을 수행하도록 하세요:
- 파일 이름을 나타내는 문자열 매개변수를 받습니다
- 파일을 열고 내용을 읽으려고 시도합니다
- 내용을 콘솔에 출력합니다
- finally 블록을 사용하여 리소스를 적절히 정리합니다
- FileNotFoundException 및 IOException을 처리합니다
파일을 찾을 수 없는 경우, "ERROR: File not found: [filename]"을 출력하세요
다른 IO 오류가 발생한 경우, "ERROR: Could not read the file: [error message]"을 출력하세요
예외가 발생했는지 여부와 관계없이 finally 블록에서 항상 "File operation completed."을 출력하세요.
치트 시트
finally 블록은 예외가 발생하든 발생하지 않든 항상 실행되는 코드를 포함하며, try 또는 catch 블록에 return 문이 있더라도 마찬가지입니다.
기본 try-catch-finally 구조:
try
{
// Code that might throw an exception
int result = 10 / 2;
Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
// Code that handles the exception
Console.WriteLine("Cannot divide by zero: " + ex.Message);
}
finally
{
// Code that always executes
Console.WriteLine("This always executes");
}
finally 블록은 파일이나 데이터베이스 연결을 닫는 등의 정리 작업에 유용합니다:
System.IO.StreamReader file = null;
try
{
file = new System.IO.StreamReader("data.txt");
string content = file.ReadToEnd();
Console.WriteLine(content);
}
catch (System.IO.FileNotFoundException)
{
Console.WriteLine("File not found.");
}
finally
{
// Always close the file, even if an exception occurred
if (file != null)
{
file.Close();
}
}
직접 해보기
using System;
using System.IO;
class Program
{
public static void ProcessData(string filename)
{
// 여기에 코드를 작성하세요
}
static void Main(string[] args)
{
string filename = Console.ReadLine();
ProcessData(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