Menu
Coddy logo textTech

error 인터페이스

Coddy GO 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 107개 중 52번째.

Go에서 오류는 error라는 내장 인터페이스를 통해 처리됩니다. 이 인터페이스는 놀라울 정도로 간단합니다. 단 하나의 메서드만 필요합니다:

type error interface {
    Error() string
}

문자열을 반환하는 Error() 메서드를 구현하는 모든 타입은 자동으로 error 인터페이스를 충족합니다. 이것이 Go의 인터페이스 시스템이 작동하는 방식입니다. 명시적인 선언이 필요하지 않습니다.

오류를 생성하는 가장 일반적인 방법은 errors 패키지를 사용하는 것입니다:

import "errors"

func Divide(a, b int) (int, error) {
    if b == 0 {
        return 0, errors.New("cannot divide by zero")
    }
    return a / b, nil
}

Go 함수는 일반적으로 마지막 반환 값으로 error를 반환합니다. error가 발생하지 않으면 nil을 반환합니다. 그런 다음 호출자는 계속 진행하기 전에 error가 nil이 아닌지 확인합니다:

result, err := Divide(10, 0)
if err != nil {
    fmt.Println("Error:", err.Error())
    return
}
fmt.Println("Result:", result)

형식이 지정된 오류 메시지를 생성하기 위해 fmt.Errorf를 사용할 수도 있습니다:

func GetUser(id int) (string, error) {
    if id <= 0 {
        return "", fmt.Errorf("invalid user id: %d", id)
    }
    return "Alice", nil
}

예외를 발생시키는 대신 오류를 반환하는 이러한 패턴은 Go의 핵심입니다. 이를 통해 오류 처리가 명시적으로 이루어지고, 문제가 발생했을 때 어떤 일이 일어나는지 고려하게 됩니다. 이는 견고한 객체 지향 코드를 작성하는 데 있어 중요한 요소입니다.

challenge icon

챌린지

쉬움

Go의 오류 처리 패턴을 보여 주는 bank account system을 만들어 봅시다. 작업을 검증하고 문제가 발생했을 때 의미 있는 오류를 반환하는 간단한 account를 만들게 됩니다.

코드를 두 개의 파일로 구성합니다:

  • account.go: 내보내진 Owner field(string)와 내보내지지 않은 balance field(float64)를 포함하는 BankAccount struct를 만듭니다. 다음을 구현합니다:
    • NewBankAccount(owner string, initialDeposit float64) (*BankAccount, error) - initial deposit이 0이거나 음수인 경우 "initial deposit must be positive" 메시지와 함께 오류를 반환하는 생성자입니다. 그렇지 않으면 account를 생성하고 반환합니다.
    • Deposit(amount float64) error - balance에 money를 추가합니다. amount가 0이거나 음수인 경우 "deposit amount must be positive" 메시지와 함께 오류를 반환합니다.
    • Withdraw(amount float64) error - balance에서 money를 차감합니다. amount가 0이거나 음수인 경우 "withdrawal amount must be positive"를 반환하고, balance가 withdrawal amount보다 작은 경우 "insufficient funds"를 반환합니다.
    • Balance() float64 - current balance를 반환합니다.
  • main.go: 입력에서 account 세부 정보와 transaction amount를 읽습니다. account를 생성하고 작업을 수행합니다. 각 작업 후 success message 또는 error message를 출력합니다.

다음 입력이 제공됩니다:

  • 1번째 line: Owner name
  • 2번째 line: Initial deposit amount
  • 3번째 line: Deposit amount
  • 4번째 line: Withdrawal amount

각 작업에 대해 결과를 출력합니다:

  • account 생성 후: Account created for [Owner] with balance: $[balance] 또는 Error: [error message]
  • deposit 후: Deposited successfully. New balance: $[balance] 또는 Error: [error message]
  • withdrawal 후: Withdrew successfully. New balance: $[balance] 또는 Error: [error message]

모든 balance 값을 소수점 이하 두 자리로 형식화합니다. account 생성에 실패하면 나머지 작업을 건너뜁니다.

예를 들어 Alice, 100, 50, 200이 주어지면 출력은 다음과 같아야 합니다:

Account created for Alice with balance: $100.00
Deposited successfully. New balance: $150.00
Error: insufficient funds

또한 Bob, -50, 25, 10이 주어지면 출력은 다음과 같아야 합니다:

Error: initial deposit must be positive

직접 해보기

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	// 소유자 이름 읽기
	ownerName, _ := reader.ReadString('\n')
	ownerName = strings.TrimSpace(ownerName)

	// Read initial deposit
	initialDepositStr, _ := reader.ReadString('\n')
	initialDeposit, _ := strconv.ParseFloat(strings.TrimSpace(initialDepositStr), 64)

	// Read deposit amount
	depositStr, _ := reader.ReadString('\n')
	depositAmount, _ := strconv.ParseFloat(strings.TrimSpace(depositStr), 64)

	// Read withdrawal amount
	withdrawStr, _ := reader.ReadString('\n')
	withdrawAmount, _ := strconv.ParseFloat(strings.TrimSpace(withdrawStr), 64)

	// TODO: NewBankAccount를 사용하여 새 은행 계좌 생성
	// 오류가 있으면 "Error: [error message]"를 출력하고 반환
	// 성공하면 "Account created for [Owner] with balance: $[balance]"를 출력

	// TODO: 입금 금액을 입금 시도
	// 오류가 있으면 "Error: [error message]"를 출력
	// If successful, print "Deposited successfully. New balance: $[balance]"

	// TODO: 출금 금액을 출금 시도
	// 오류가 있으면 "Error: [error message]"를 출력
	// If successful, print "Withdrew successfully. New balance: $[balance]"

	// 잔액 값을 소수점 두 자리로 포맷하려면 fmt.Printf("%.2f", balance)를 사용하세요

	_ = ownerName
	_ = initialDeposit
	_ = depositAmount
	_ = withdrawAmount
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Go 컴파일러