본문 바로가기
공부,일/C#

예외처리

by fromnothing1 2021. 6. 10.

예외 처리 

try,catch

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


class Program
{
  

 
    static void Main(string[] args)
    {
        int iNumer;
        Console.Write("정수를 입력하세요: ");
        try // 예외 발생을 감시하는 구간
        {
            iNumer = int.Parse(Console.ReadLine());
            // 위코드에서 잘못된 입력시 프로그램을 중지하고,
            // 닷넷 프레임워크에서 예외 객체를 생성한다. 
            // 생성된 예외 객체는 catch 문에 던져 준다. 
            // 지금의 경우 FormatException  객체가 생성된다.
        }
        catch (FormatException Result) // 예외를 처리하는 부분
        {// FormatException 만 처리하겠다.
            //Result 에러에 대한 정보를 담고 있다.
            Console.WriteLine("입력이 잘못 되었습니다. ");
            Console.WriteLine(Result.Message);
            iNumer = 0;
        }
        catch (Exception)  // 밑에가 포관적인 예외 
        // Exception 모든 예외를 처리하겠다.
        {
            Console.WriteLine("문제가 생겼습니다. ");
            iNumer = 0;

        }
        Console.WriteLine("정수 값 : "+iNumer);

    }


}

예외 처리에서 catch 문은 여러번 사용가능하다. 

순서대로 catch 하기 때문에 뒤에 있는 catch 문일 수록 포관적인 예외를 다뤄야 한다. 

 

finally

공통적으로 예외처리가 끝나고 반드시 수행되어야 되는 코드 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
{

    static void Main(string[] args)
    {

        Console.Write("입력 : ");

        string input = Console.ReadLine();

        try
        {
            int index = int.Parse(input);
            Console.WriteLine("입력 숫자 : " + index);

        }
        catch (Exception e)
        {
            Console.WriteLine("예외가 발생했습니다.");
            Console.WriteLine(e.GetType());
            
        }
        finally
        {
            Console.WriteLine("프로그램이 종료 되었습니다.");
        }   

    }

}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
{

    static void Main(string[] args)
    {

        Console.Write("입력 : ");

        string input = Console.ReadLine();

        try
        {
            int index = int.Parse(input);
            Console.WriteLine("입력 숫자 : " + index);

        }
        catch (Exception e)
        {
            Console.WriteLine("입력이 잘못 되어 종료합니다.");
            return;
        }
        finally
        {
            Console.WriteLine("finally 수행");
        }
    }
}

위에서 알 수 있다 싶이 return 으로 함수가 끝나더라도 finally 는 반드시 수행된다. 

 

throw 

발생한 예외를 catch 로 던져주는 함수 

catch 가 없다면 닷넷으로 전달해준다.

 

      static void Main3(string[] args)
    {
        // 예외 객체생성
        Exception aException;
        aException = new Exception();
        try
        {
            throw aException;
        }
        catch (Exception)
        {
            Console.WriteLine("우리가 잡는 경우");
            throw; // 닷넷에 catch() 안에있는 Exception 을 던져줌 
        }
        Console.WriteLine("할룽"); //catch 문으로 우리가 잡았기 때문에 프로그램 정상 동작
    }
    static void Main2(string[] args)
    {
        // 예외 객체생성
        Exception aException;
        aException = new Exception();
        try
        {
            throw aException; 
        }
        catch (Exception)
        {

            Console.WriteLine("우리가 잡는 경우");
        }
        Console.WriteLine("할룽"); //catch 문으로 우리가 잡았기 때문에 프로그램 정상 동작
    }
    static void Main1(string[] args)
    {
        // 예외 객체생성
        Exception aException;
        aException = new Exception();
        //throw 가상머신(.Net) 한테 예외를 준다.
        throw aException; // 예외 발생
        Console.WriteLine("할룽"); // 예외가 발생했기 때문에 프로그램이 중단되서 실행되지 않는다.


    }
   

 

'공부,일 > C#' 카테고리의 다른 글

WinForms DataGridView  (0) 2021.06.11
Window Forms 리스트 박스 ,콤보 박스  (0) 2021.06.11
enum 열거형 다중지정 방식  (0) 2021.06.10
210608  (0) 2021.06.08
소코반게임 만들기  (0) 2021.06.08

댓글