C#교과서 마스터하기 16. 예외 처리(Exception Handling)

min seung moon·2021년 7월 10일
0

C#

목록 보기
16/54

https://www.youtube.com/watch?v=C781teBX52U&list=PLO56HZSjrPTB4NxAsEP8HRk6YKBDLbp7m&index=46

1. 예외의 의미

  • 프로그램 실행 도중 발생하는 예상치 못한 오류
    • 오류(Error) === 예외(Exception)
  • 처리되지 않은 예외는 프로그램의 실행을 중단시키는 원인
    • 강제 종료 => 정상 종료로 처리가 필요
  • 신뢰도 및 안전성 측면에서 매우 중요
    • 예외 처리(Exception Handling)를 통한 강제 종료 방지

2. 예외(오류)의 종류

01. 문법(컴파일) 오류

  • 잘못된 명령어를 입력
  • 타이핑의 실수로 발생
  • 문법 오류를 방지하려면 많은 예제를 접해가면서 프로그래밍의 기초 문법을 확실하게 이해해야 함

02. 런타임 오류

  • 런타임 오류는 프로그램 작성 후 실행할 때 발생하는 오류
  • 많은 테스트를 통해서 해결

03. 알고리즘(논리) 오류

  • 주어진 문제에 대한 잘못된 해석으로 잘못된 결과를 초래하는 에러를 알고리즘 오류 또는 로직 오류라고 한다
    • 요청(A + B) 오류 코드(A * B)
  • 문법 오류나 런타임 오류는 쉽게 발견해 낼 수 있지만, 알고리즘 오류는 처리 결과가 틀리게 나왔는데도 알 수 없는 경우가 많기 때문에 이 알고리즘 오류를 해결하기가 가장 어렵다
  • 알고리즘 오류를 해결하기 위해서는 많은 책을 통해서 코드 분석 및 많은 코드를 직접 만들어 보는 등 오류를 찾아내는 능력을 키워야 함
    • 프로그래밍 경험 필요

3. throw 구문

  • 예외를 직접 발생시킴
  • 구문
    • throw expression;
  • throwing

4. Try/Catch/Finally Block

  • 예외 처리 구문

5. 예외 처리(Exception Handling)

  • try-catch-finally와 throw를 사용하여 예외 처리

01. System.IndexOutOfRangeException

-1. 직접 예외 처리 메시지 작성

using System;
using static System.Console;

namespace testProject
{
    class Program
    {

        static void Main(string[] args)
        {
            try
            {
                int[] arr = new int[2];
                arr[100] = 1234; // 예외 발생(System.IndexOutOfRangeException)
            }
            catch (Exception)
            {
                WriteLine("에러가 발생");
            }
        }
    }
}

-2. 예외처리 객체 사용한 메시지 전달

using System;
using static System.Console;

namespace testProject
{
    class Program
    {

        static void Main(string[] args)
        {
            try
            {
                int[] arr = new int[2];
                arr[100] = 1234; // 예외 발생(System.IndexOutOfRangeException)
            }
            catch (Exception e) // Exception e변수에는 예외에 대한 상세 정보가 담김
            {
                WriteLine(e.Message);
            }
        }
    }
}

02. FormatException

using System;
using static System.Console;

namespace testProject
{
    class Program
    {

        static void Main(string[] args)
        {
            string inputNumber = "3.14";
            int number = 0;

            try
            {
                number = Convert.ToInt32(inputNumber);
                WriteLine($"입력한 값 : {number}");
            }
            catch (FormatException fe)
            {
                WriteLine($"에러 발생 : {fe.Message}");
                WriteLine($"{inputNumber}는 정수여야 합니다.");
            }
        }
    }
}

03. Exception

-1. 런타임 예외 발생

using System;
using static System.Console;

namespace testProject
{
    class Program
    {

        static void Main(string[] args)
        {
            try
            {
                int now = DateTime.Now.Second;
                WriteLine($"[0] 현재 초 : {now}");

                int result = 2 / (now % 2);
                WriteLine("[1] 홀수 초에서는 정상 처리");
            }
            catch 
            {
                WriteLine("[2] 짝수 초에서는 런타임 에러 발생");
            }
        }
    }
}

04. finally

  • 정상 & 비정상 상관 없이 마지막에 실행
using System;
using static System.Console;

namespace testProject
{
    class Program
    {

        static void Main(string[] args)
        {
            int x = 5, y = 0, r;

            try
            {
                r = x / y;
                WriteLine($"{x} / {y} = {r}");
            }
            catch (Exception e)
            {
                WriteLine($"예외 발생 : {e.Message}");
            }
            finally
            {
                WriteLine("프로그램 종료");
            }
        }
    }
}


05. throw

-1. throw 사용 방법

using System;
using static System.Console;

namespace testProject
{
    class Program
    {

        static void Main(string[] args)
        {
            throw new ArgumentException();
        }
    }
}

using System;
using static System.Console;

namespace testProject
{
    class Program
    {

        static void Main(string[] args)
        {
            WriteLine("[1] 시작");

            try
            {
                WriteLine("[2] 실행");
                throw new Exception(); // 일단 에러 발생
            }
            catch(Exception e)
            {
                WriteLine($"[3] 에러발생 : {e.Message}");
            }
            finally
            {
                WriteLine("[4]프로그램 종료");
            }
        }
    }
}

-2. 5.3.1 예외처리 구문 변경

using System;
using static System.Console;

namespace testProject
{
    class Program
    {

        static void Main(string[] args)
        {
            try
            {
                int now = DateTime.Now.Second;
                WriteLine($"[0] 현재 초 : {now}");

                if (now % 2 == 0) throw new Exception();
                WriteLine("[1] 홀수 초에서는 정상 처리");
            }
            catch(Exception e)
            {
                WriteLine(e.Message);
                WriteLine("[2] 짝수 초에서는 런타임 에러 발생");
            }
        }
    }
}



-3. 예외에 메시지 넣어서 보내기

using System;
using static System.Console;

namespace testProject
{
    class Program
    {

        static void Main(string[] args)
        {
            try
            {
                int now = DateTime.Now.Second;
                WriteLine($"[0] 현재 초 : {now}");

                if (now % 2 == 0) throw new Exception("[2] 짝수 초에서는 런타임 에러 발생");
                WriteLine("[1] 홀수 초에서는 정상 처리");
            }
            catch(Exception e)
            {
                WriteLine(e.Message);
            }
        }
    }
}

profile
아직까지는 코린이!

0개의 댓글