Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

18. DivideByZeroException과 try~catch문 본문

초보자를 위한 C# 200제/C# 입문

18. DivideByZeroException과 try~catch문

빌드이너프 2024. 9. 12. 20:46

C#에서는 실행 중에 나오는 에러를 예외(Exception)라고 한다.

산술 연산에서 나올 수 있는 예외는 나눔 예외(DivideByZeroException)와 오버플로우 예외(OverflowException)

 

코드1

using System;

namespace A018_DivideByZero
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 10, y = 0;
            Console.WriteLine(10.0 / y);
            Console.WriteLine(x / y);
        }
    }
}

 

실행1

 

코드2(try~catch 문 사용)

using System;

namespace A018_DivideByZero
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 10, y = 0;

            try
            {
                Console.WriteLine(x / y);
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}

 

실행2