전체 코드

using GiftBoxManagerNamespace;
using GiftBoxNamespace;
using System;
using System.Collections;
using System.ComponentModel;
using System.Text;

namespace C_
{

    class Program
    {
        static GiftBox giftBox = new GiftBox();
        static void Main(string[] args)
        {
            // try - catch
            // 파일 리드
            // 네트워크 에서 필수적으로 사용되는 중이다.
            try
            {
                Console.WriteLine("래터 출력하는 부분");
                Console.WriteLine(giftBox.Letter);
            }
            catch (NullReferenceException e)
            {
                Console.WriteLine("NullReferenceException e:");
                Console.WriteLine(e);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception e:");
                Console.WriteLine(e);
            }
            finally
            {
                Console.WriteLine("무조건 실행");
            }

            Console.WriteLine("종료");

            //배열 길이 맞지 않는 경우

            int[] ints = { 1, 2, 3 };
            if (ints.Length > 4)
            {
                Console.WriteLine(ints[4]);
            }


        }
       


        
    }
}

1. 예외(Exception)란?

  • 프로그램 실행 중 발생하는 예상하지 못한 오류예외(Exception) 라고 합니다.
  • 예외를 적절히 처리하지 않으면 프로그램이 강제 종료될 수 있습니다.
  • try-catch-finally 구문을 사용하여 예외를 처리할 수 있습니다.

2. try-catch-finally 기본 구조

try
{
    // 오류가 발생할 가능성이 있는 코드
}
catch (Exception e)
{
    // 예외가 발생하면 실행되는 코드
}
finally
{
    // 예외 발생 여부와 상관없이 실행되는 코드
}
  • try : 오류가 발생할 가능성이 있는 코드를 작성하는 블록.
  • catch : 예외가 발생하면 실행되는 블록.
  • finally : 오류 발생 여부와 관계없이 실행되는 블록.

3. try-catch 기본 예제

static GiftBox giftBox;

static void Main(string[] args)
{
    Console.WriteLine("프로그램 시작");

    try
    {
        Console.WriteLine("래터 출력 시도");
        Console.WriteLine(giftBox.Letter); // giftBox가 null이므로 예외 발생
    }
    catch (NullReferenceException e) // 특정 예외 처리
    {
        Console.WriteLine("NullReferenceException 발생:");
        Console.WriteLine(e);
    }
    catch (Exception e) // 모든 예외 처리
    {
        Console.WriteLine("Exception 발생:");
        Console.WriteLine(e);
    }
    finally
    {
        Console.WriteLine("무조건 실행되는 finally 블록");
    }

    Console.WriteLine("프로그램 종료");
}

✔️ 분석

  • giftBox가 초기화되지 않아 NullReferenceException 발생.
  • catch (NullReferenceException e)가 먼저 실행되어 예외를 처리.
  • finally 블록은 예외 발생 여부와 상관없이 실행됨.

4. 여러 개의 catch 블록 사용

try
{
    Console.WriteLine("래터 출력 시도");
    Console.WriteLine(giftBox.Letter);
}
catch (NullReferenceException e)
{
    Console.WriteLine("Null 값 참조 오류 발생");
}
catch (IndexOutOfRangeException e)
{
    Console.WriteLine("배열 인덱스 초과 오류 발생");
}
catch (Exception e)
{
    Console.WriteLine("기타 오류 발생");
}
finally
{
    Console.WriteLine("무조건 실행되는 finally 블록");
}

✔️ 분석

  • catch 블록을 여러 개 사용할 수 있으며, 더 구체적인 예외를 먼저 처리해야 합니다.
  • 예를 들어, NullReferenceException이 발생하면 해당 catch에서 처리되고,
    다른 catch 블록은 실행되지 않습니다.

5. 배열 길이 검사 후 접근

배열을 다룰 때 길이를 검사하지 않으면 IndexOutOfRangeException 예외 발생 가능.

int[] numbers = { 1, 2, 3 };

if (numbers.Length > 4) // 배열 길이 검사
{
    Console.WriteLine(numbers[4]); // IndexOutOfRangeException 방지
}

✔️ 예외 방지

  • 배열 길이를 확인하고 접근하면 IndexOutOfRangeException 방지 가능.

6. try-catch를 반드시 사용해야 하는 경우

  1. 파일 읽기/쓰기
    • 파일이 존재하지 않거나, 접근 권한이 없을 때 예외 발생 가능.
  2. 네트워크 요청 (API 호출)
    • 서버가 응답하지 않거나, 잘못된 데이터를 반환할 때 예외 발생 가능.
  3. 데이터베이스 연결
    • 데이터베이스 접속 오류나 쿼리 실행 오류 발생 가능.

7. 실제 응용 예제

7-1. 파일 읽기 예제

using System;
using System.IO;

class Program
{
    static void Main()
    {
        try
        {
            string content = File.ReadAllText("nonexistentfile.txt"); // 존재하지 않는 파일
            Console.WriteLine(content);
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine("파일을 찾을 수 없습니다.");
        }
        catch (Exception e)
        {
            Console.WriteLine("오류 발생:");
            Console.WriteLine(e);
        }
        finally
        {
            Console.WriteLine("파일 읽기 작업 종료");
        }
    }
}

✔️ 분석

  • File.ReadAllText("nonexistentfile.txt") → 파일이 없으면 FileNotFoundException 발생.
  • catch (FileNotFoundException e)에서 파일을 찾을 수 없을 때의 오류 처리.
  • finally 블록에서 파일 작업 종료 메시지 출력.

7-2. 네트워크 요청 예제

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        try
        {
            HttpClient client = new HttpClient();
            string response = await client.GetStringAsync("https://invalidurl.com");
            Console.WriteLine(response);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("HTTP 요청 실패:");
            Console.WriteLine(e.Message);
        }
        finally
        {
            Console.WriteLine("네트워크 요청 종료");
        }
    }
}

✔️ 분석

  • HttpClient를 사용해 웹 요청을 보내지만, 잘못된 URL이면 HttpRequestException 발생.
  • catch (HttpRequestException e)에서 네트워크 오류 처리.

profile
李家네_공부방

0개의 댓글