연습 - C# 콘솔 애플리케이션에서 예외 throw 및 catch

완료됨

이 연습에서는 최상위 문에서 try 코드 블록 및 catch 절을 개발하고, MakeChange 메서드에서 예외를 만들고 throw한 다음, 예외 개체를 사용하여 catch 코드 블록을 완성합니다. 이 연습에서는 다음 작업을 완료합니다.

  1. 최상위 문 업데이트: 최상위 문에서 try-catch 패턴을 구현합니다. try 코드 블록에는 MakeChange 호출이 포함됩니다.
  2. MakeChange 메서드 업데이트: "현금출납기 현금 부족" 및 "미지급" 문제에 대한 예외를 만들고 throw합니다.
  3. throw된 예외의 속성을 사용하도록 catch 코드 블록을 업데이트합니다.
  4. 확인 테스트: 이 연습에서 개발하는 코드에 대한 확인 테스트를 수행합니다.

최상위 문에 try-catch 패턴 추가

이 작업에서는 MakeChange 문 내에 try 메서드 호출을 묶고 해당 catch 절을 만듭니다.

  1. Visual Studio Code 편집기에서 Program.cs 파일이 열려 있는지 확인합니다.

  2. 다음 코드 줄을 찾습니다.

    // MakeChange manages the transaction and updates the till 
    string transactionMessage = MakeChange(itemCost, cashTill, paymentTwenties, paymentTens, paymentFives, paymentOnes);
    
    // Backup Calculation - each transaction adds current "itemCost" to the till
    if (transactionMessage == "transaction succeeded")
    {
        Console.WriteLine($"Transaction successfully completed.");
        registerCheckTillTotal += itemCost;
    }
    else
    {
        Console.WriteLine($"Transaction unsuccessful: {transactionMessage}");
    }
    
  3. 잠시 시간을 내어 이 코드의 용도를 생각해 보세요.

    MakeChange는 문자열 값을 반환합니다. 이 반환 값은 transactionMessage이라는 변수에 할당됩니다. transactionMessage가 "transaction succeeded"와 일치하면 구매한 항목의 비용이 registerCheckTillTotal에 추가됩니다. registerCheckTillTotal 변수는 MakeChange 메서드에서 계산된 현금출납기 잔액을 확인하는 데 사용됩니다.

  4. MakeChange 문 코드 블록 내에 try 메서드 호출을 묶으려면 코드를 다음과 같이 업데이트합니다.

    try
    {
        // MakeChange manages the transaction and updates the till 
        string transactionMessage = MakeChange(itemCost, cashTill, paymentTwenties, paymentTens, paymentFives, paymentOnes);
    }
    
  5. catch 문 코드 블록 뒤에 다음 try 절을 추가합니다.

    catch
    {
    }
    

    예외를 만들고 throw하면 catch 절 개발은 완료됩니다.

MakeChange 메서드에서 예외 만들기 및 throw

이 작업에서는 거래를 완료할 수 없는 경우 사용자 지정 예외를 만들고 throw하도록 MakeChange를 업데이트합니다.

MakeChange 메서드에는 예외가 발생해야 하는 두 가지 문제가 포함됩니다.

  • 미지급 문제: 이 문제는 고객이 항목 비용보다 적은 금액을 지불하는 경우에 발생합니다. 고객이 충분한 결제를 제공하지 않은 경우 MakeChange는 예외를 throw해야 합니다.

  • 현금출납기 현금 부족: 이 문제는 현금출납기에 정확한 거스름돈을 지불하는 데 필요한 지폐가 포함되어 있지 않을 때 발생합니다. 현금출납기가 정확한 거스름돈을 지불할 수 없는 경우 MakeChange는 예외를 throw해야 합니다.

  1. MakeChange 메서드가 나올 때까지 아래로 스크롤합니다.

  2. 다음 코드 줄을 찾습니다.

    if (changeNeeded < 0)
        transactionMessage = "Not enough money provided.";
    
  3. 잠시 시간을 내어 이 코드가 해결하는 문제를 생각해 보세요.

    changeNeeded가 0보다 작은 경우 고객은 구매하는 항목의 구매 가격을 충당하기에 충분한 금액을 제공하지 않은 것입니다. 구매 가격 및 고객이 제공한 금액이 MakeChange 메서드의 매개 변수입니다. 고객이 충분한 금액을 제공하지 않으면 메서드가 거래를 완료할 수 없습니다. 즉, 작업이 실패합니다.

    다음 조건과 일치하는 두 가지 예외 유형이 있습니다.

    • InvalidOperationException: InvalidOperationException 예외는 메서드의 작동 조건이 특정 메서드 호출의 성공적인 완료를 지원하지 않는 경우에만 throw되어야 합니다. 이 경우 작동 조건은 메서드에 제공된 매개 변수에 의해 설정됩니다.
    • ArgumentOutOfRangeException - ArgumentOutOfRangeException 예외는 인수 값이 호출된 메서드가 정의한 값의 허용 범위를 벗어나는 경우에만 throw 되어야 합니다. 이 경우 제공된 금액이 항목 비용보다 커야 합니다.

    두 예외 유형 모두 작동할 수 있지만 InvalidOperationException이 이 애플리케이션의 컨텍스트에서 약간 더 적합합니다.

  4. 코드를 다음과 같이 업데이트합니다.

    if (changeNeeded < 0)
        throw new InvalidOperationException("InvalidOperationException: Not enough money provided to complete the transaction.");
    
  5. 아래로 스크롤하여 다음 코드 줄을 찾습니다.

    if (changeNeeded > 0)
        transactionMessage = "Can't make change. Do you have anything smaller?";
    
  6. 잠시 시간을 내어 이 코드가 해결하는 문제를 생각해 보세요.

    거스름돈을 준비하는 changeNeeded 루프 이후에 while가 0보다 크면 현금출납기가 거스름돈에 사용할 수 있는 지폐가 소진된 것입니다. 현금출납기에 거스름돈 지불에 필요한 지폐가 부족하면 메서드가 거래를 완료할 수 없습니다. 즉, 작업이 실패합니다.

    InvalidOperationException 예외를 사용하여 예외를 만들어야 합니다.

  7. 코드를 다음과 같이 업데이트합니다.

    if (changeNeeded > 0)
        throw new InvalidOperationException("InvalidOperationException: The till is unable to make the correct change.");
    

catch 코드 블록 완성

이 작업에서는 특정 예외 유형을 catch하도록 catch 절을 업데이트합니다.

  1. MakeChange 메서드 위로 스크롤하여 다음 코드를 찾습니다.

    catch
    {
    }    
    
  2. MakeChange 메서드에서 throw된 예외 유형을 catch하려면 다음과 같이 코드를 업데이트합니다.

    catch (InvalidOperationException e)
    {
        Console.WriteLine($"Could not complete transaction: {e.Message}");
    }    
    

    InvalidOperationException에서 throw된 MakeChange 예외 개체는 catch되지만 다른 예외 유형은 catch되지 않습니다. 다른 예외 유형은 처리할 준비가 되지 않았기 때문에 호출 스택의 하위 수준에서 catch되도록 하는 것이 중요합니다. MakeChange 내에서 다른 예외 유형이 예상될 때 catch 절을 더 추가할 수 있습니다.

  3. 파일 메뉴를 사용하여 업데이트를 저장합니다.

MakeChange 메서드를 "string"에서 "void"로 변환하고 예외 속성에 액세스합니다.

이 작업에서는 MakeChangevoid 형식으로 업데이트한 다음 예외 속성을 사용하여 사용자에게 문제 세부 정보를 전달합니다.

  1. MakeChange 메서드 맨 위로 스크롤합니다.

  2. MakeChange 메서드를 string 형식에서 void 형식으로 변환하려면 다음과 같이 코드를 업데이트합니다.

    static void MakeChange(int cost, int[] cashTill, int twenties, int tens = 0, int fives = 0, int ones = 0)
    
  3. 다음 변수 선언을 삭제합니다.

    string transactionMessage = "";
    
  4. MakeChange 메서드 맨 아래로 스크롤합니다.

  5. 다음 코드 줄을 삭제합니다.

    if (transactionMessage == "")
        transactionMessage = "transaction succeeded";
    
    return transactionMessage;
    
  6. 최상위 문까지 스크롤하여 try 코드 블록을 찾습니다.

  7. try 코드 블록을 다음과 같이 업데이트합니다.

    try
    {
        // MakeChange manages the transaction and updates the till 
        MakeChange(itemCost, cashTill, paymentTwenties, paymentTens, paymentFives, paymentOnes);
    
        Console.WriteLine($"Transaction successfully completed.");
        registerCheckTillTotal += itemCost;
    }
    
  8. 다음 코드 줄을 찾아 삭제합니다.

    // Backup Calculation - each transaction adds current "itemCost" to the till
    if (transactionMessage == "transaction succeeded")
    {
        Console.WriteLine($"Transaction successfully completed.");
        registerCheckTillTotal += itemCost;
    }
    else
    {
        Console.WriteLine($"Transaction unsuccessful: {transactionMessage}");
    }
    
    

    trycatch 코드 블록은 이제 거래 "성공" 및 "실패" 메시지를 사용자에게 전달합니다. 예외의 Message 속성은 문제를 설명하므로 단일 Console.WriteLine() 문이 두 문제를 모두 해결합니다. 이렇게 업데이트하면 코드를 더 쉽게 읽고 유지 관리할 수 있습니다.

  9. 파일 메뉴를 사용하여 업데이트를 저장합니다.

작업 확인

이 작업에서는 애플리케이션을 실행하고 업데이트된 코드가 의도한 대로 작동하는지 확인합니다.

  1. 위로 스크롤하여 최상위 문에서 루프를 while 찾습니다.

    이 루프는 거래를 반복하는 데 사용됩니다.

  2. while 루프가 시작되기 몇 줄 전에 다음 코드를 찾습니다.

    int transactions = 10;
    
    
  3. 다음과 같이 거래 수를 40으로 업데이트합니다.

    int transactions = 40;
    
    
  4. while 루프 내에서 다음 코드 줄을 찾습니다.

    int itemCost = valueGenerator.Next(2, 20);
    
    
  5. itemCost 난수 생성기를 다음과 같이 업데이트합니다.

    int itemCost = valueGenerator.Next(2, 50);
    
    

    이 비용 범위가 고객이 구매할 항목에 더 적합합니다.

  6. 파일 메뉴를 사용하여 업데이트를 저장합니다.

  7. 실행 메뉴에서 디버깅 시작을 선택합니다.

  8. 터미널 패널에서 출력을 검토합니다.

  9. 두 예외 유형과 연결된 메시지가 표시되는지 확인합니다.

    거래 보고서에는 다음 "Could not complete transaction" 메시지가 포함되어야 합니다.

    Customer is making a $42 purchase
             Using 2 twenty dollar bills
             Using 0 ten dollar bills
             Using 0 five dollar bills
             Using 0 one dollar bills
    Could not complete transaction: InvalidOperationException: Not enough money provided to complete the transaction.
    
    Customer is making a $23 purchase
             Using 2 twenty dollar bills
             Using 0 ten dollar bills
             Using 0 five dollar bills
             Using 1 one dollar bills
    Cashier prepares the following change:
             A five
             A five
             A one
             A one
    Could not complete transaction: InvalidOperationException: The till is unable to make change for the cash provided.
    
    

축하합니다. 코드 논리 문제를 해결하기 위해 금전등록기 애플리케이션을 디버그했으며 적절한 예외 처리 기술을 사용하도록 애플리케이션을 업데이트했습니다.

참고

보고된 출력은 현금출납기 잔액이 더 이상 정확하지 않음을 보여줍니다. 코드에 다른 논리 버그가 있습니다. Visual Studio Code 디버깅 기술을 시연하려는 경우 과제 프로젝트 모듈을 사용할 수 있습니다.