본문 바로가기
Study/C#

[C#][Study][기초다지기] 예외처리

by 스테디코디스트 2023. 9. 23.
반응형

예외처리

- try : 예외를 일으킬 수 있는 코드 식별

- catch : 예외처리

- throw : 사용자 정의 예외 메시지 생성

- finally : 예외 발생 여부에 관계없이 실행

[ex]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Exception_Handling
{
    class Program
    {
        static void Main(string[] args)
        {
            label:
            // Try block: 런타임에 발생하는 예외를 확인한다.
            try
            {
                int num1, num2;
                decimal result;
                
                Console.WriteLine("Divide Program. You Enter 2 number and we return result");
                Console.WriteLine("Enter 1st Number: ");
                num1 = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Enter 2nd Number: ");
                num2 = Convert.ToInt32(Console.ReadLine());
 
                result =(decimal)num1 / (decimal)num2;
                Console.WriteLine("Divide : " + result.ToString());
                Console.ReadLine();
            }
 
           // 예외 처리를 위한 다중 catch 문 
            catch (DivideByZeroException dex)
            {
                Console.WriteLine("You have Entered 0");
                Console.WriteLine("More Details about Error: \n\n" + dex.ToString() + "\n\n");
                goto label;
            }
 
            catch (FormatException fex)
            {
                Console.WriteLine("Invalid Input");
                Console.WriteLine("More Details about Error: \n\n" + fex.ToString() + "\n\n");
                goto label;
            }
 
            // Parent Exception : 모든 유형의 예외를 찾아냄 
            catch (Exception ex)
            {
                Console.WriteLine("Other Exception raised" + ex.ToString() + "\n\n");
                goto label;
            }
 
           // Finally block: 항상 실행됨 
            finally
            {
                Console.WriteLine("Finally Block: For Continue Press Enter and for Exit press Ctrl + c");
                Console.ReadLine();
            }
        }
    }
}

 

- checked : 오버플로 발생시 처리

- unchecked : 오버플로 무시하고 처리

[ex]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Checked_Unchecked
{
    class Program
    {
        static void Main(string[] args)
        {
        	// sbyte는 -128 ~ 127 범위 -> 20*30 = 600 -> 오버플로우 발생
            sbyte num1 = 20, num2 = 30, result;
            try
            {
                unchecked // 오버플로우에 관계없이 실행
                {
                    result = (sbyte)(num1 * num2);
                    Console.WriteLine("{0} x {1} = {2}", num1, num2, result);
                }
                checked // 오버플로 감지 시 실행
                {
                    result = (sbyte)(num1 * num2);
                    Console.WriteLine("{0} x {1} = {2}", num1, num2, result);
                }
            }
            catch (OverflowException oex)
            {
                Console.WriteLine(oex.Message);
            }
            Console.ReadKey();
        }
    }
}