C# 기초

C# Exception Handling: try, catch and finally

Handle the failures you expect and keep your program running. Learn when to validate and when to catch.

  • 초급
  • 2분 분량
  • 실행 가능한 예제 1개
배울 내용
  • try, catch and finally
  • Catching specific exception types
  • TryParse instead of exceptions for normal checks
Handling a risky call
  1. 1try { ... }Run the code that can fail
  2. 2catch (FormatException)Handle the expected failure
  3. 3finally { ... }Clean up every time

Validate first, catch what you cannot prevent

예외는 프로그램이 비정상적인 상황을 만났을 때 오류를 알리는 방법입니다. 형식이 잘못된 숫자처럼 예상할 수 있는 오류라면, C#에서는 오류가 일어난 뒤 잡는 것보다 TryParse 같은 메서드로 먼저 확인하는 것을 권장합니다.

int.TryParse 메서드는 문자열 "42"를 숫자로 바꾸려 시도합니다. 성공하면 결과가 value에 들어가고 프로그램은 84를 출력하며, 실패하면 Invalid number라는 메시지를 출력합니다. 이 방법이 더 빠르고 알기 쉽습니다. try/catch 블록은 라이브러리가 예외를 던져 오류를 알릴 때 씁니다.

핵심 포인트

  1. Use TryParse and similar checks for ordinary bad input.
  2. catch specific types such as FormatException, not every Exception.
  3. finally runs whether or not an exception happened.

실행 가능한 C# 예제

C#
코드 실행 →
Program.cs
using System;

class Program
{
    static void Main()
    {
        string input = "42";
        if (int.TryParse(input, out int value))
            Console.WriteLine(value * 2);
        else
            Console.WriteLine("Invalid number");
    }
}
이 예제의 실행 버튼 만들기 실행 결과
84

디버거로 연습하기

중요한 대입이나 조건에 중단점을 두고 Debug를 눌러 다음 줄로 넘어가기 전에 지역 변수 값을 확인하세요.

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지