관리 메뉴

IT 쟁이

C# 예외처리예제 SimpleExceptions 본문

Microsoft(C#).NET

C# 예외처리예제 SimpleExceptions

클라인STR 2008. 1. 14. 10:59

using System;

namespace Wrox.ProfessionalCSharp.Chapter6.SimpleExceptions
{
 /// <summary>
 /// Class1에 대한 요약 설명입니다.
 /// </summary>
 public class MainEntryPoint
 {
  /// <summary>
  /// 해당 응용 프로그램의 주 진입점입니다.
  /// </summary>
  [STAThread]
  static void Main(string[] args)
  {
   string userInput;
   while(true)
   {
    try
    {
     Console.Write("Input a number between 0 and 5 " + "(or just hit return to exit)>");

     userInput = Console.ReadLine();
     if(userInput == "")
      break;
     int index = Convert.ToInt32(userInput);
     if(index <0 || index >5)
      throw new IndexOutOfRangeException("You typed in " + userInput);
     Console.WriteLine("Your number was " + index);
    }
    catch (IndexOutOfRangeException e)
    {
     Console.WriteLine("Exception: " + "Number should be between 0 and 5." + e.Message);
    }
    catch (Exception e)
    {
     Console.WriteLine("An exception was thrown. Message was : " + e.Message);
    }
    catch
    {
     Console.WriteLine("Some othre exception has occurred");
    }
    finally
    {
     Console.WriteLine("Thank you");
    }
   

   }
  }
 }
}

사용자 삽입 이미지


이 프로그램은 프로그램이 종료되기전까지 루프가 실행되어  Console.ReadLine()을 이용하여 사용자의 입력을 요구한다음 System.Convert.ToInt32()메소드를 이용하여 문자열을 int로 변환한다.

이때 예외가 발생할 경우 즉 0  - 5 사이에 숫자값이 입력되면 IndexOutOfRangeException()이 실행하고 Console.WriteLine.. 문장이 실행된다. catch{}블록에서 빠져나와 finally 블록을 실행하게 된다. 그리고는 또다시 입력을 반복하게 된다. 이때 만약 사용자가 숫자 이외예 a 또는

다른 문자를 입력했을경우 FormatException 이발생하는데 이는 Exception 범주에 속하므로 catch(Exception) 블록이 실행된다.

만약에 catch블록의 순서가 1, 2번째가 바뀐다면 컴파일 타임시 오류가 발생할것이다.


Comments