Error handling with return codes · 리턴 코드를 이용한 오류 처리
C has no try/except
- Some languages throw exceptions when something goes wrong. C does not have exceptions.
- Instead, a C function reports trouble through its return value — a status code.
- The caller checks that code after every call and decides what to do.
C에는 try/except가 없습니다
- 일부 언어에서는 오류 발생 시 예외(exception)를 던집니다. C에는 예외가 없습니다.
- 대신 C 함수는 반환값(return value) — 즉 상태 코드(status code)를 통해 문제를 보고합니다.
- 호출侧(code)은 모든 호출 후 해당 코드를 확인하고 대응방식을 결정합니다.
Return a status code
- A common rule: return
0for success and a negative number like-1for failure. - So
int do_thing(...)returns0when it worked,-1when it could not. - The real "answer" is then handed back a different way (see the next step).
상태 코드 반환
- 일반적인 규칙: 성공 시
0를 반환하고, 실패 시-1와 같은 음수 값을 반환합니다. - 따라서
int do_thing(...)는 작동했을 때0을, 작동하지 못했을 때-1을 반환합니다. - 실제 '정답'은 다른 방식으로 전달됩니다 (다음 단계 참고).
Reporting the answer through an out-pointer
- If the return value is a status code, where does the real result go? Through an out-pointer.
- The caller passes the address of a variable; the function writes the answer with
*. - On failure, the function returns
-1and simply leaves that variable alone.
out-pointer를 통한 정답 보고
- 반환값이 상태 코드라면, 실제 결과는 어디로 갈까요? out-pointer를 통해입니다.
- 호출자가 변수의 주소를 전달하면, 함수는
*로 답을 씁니다. - 실패 시, 함수는
-1를 반환하고 해당 변수에는 아무런 변경도 가하지 않습니다.
Sentinels for "no value"
- A sentinel is a special value that means "nothing here":
-1for an index,NULLfor a pointer. - Functions use sentinels so the caller can tell success from failure with a simple check.
- Always check for the sentinel before you trust the result.
"값 없음"을 나타내는 sentinel
- sentinel은 '여기에 값이 없다'는 의미를 가진 특수한 값입니다: 인덱스에는
-1, 포인터에는NULL를 사용합니다. - 함수는 caller가 간단한 검사로 성공과 실패를 구분할 수 있도록 sentinel을 사용합니다.
- 결과에 신뢰하기 전에는 반드시 sentinel 값을 확인해야 합니다.
#include <stdio.h>
int safe_div(int a, int b, int *result) {
if (b == 0) return -1; // failure: cannot divide by zero
*result = a / b; // success: hand back the answer
return 0;
}
int main(void) {
int r;
if (safe_div(10, 2, &r) == 0) {
printf("%d\n", r); // 5
}
return 0;
}
Common mistakes
- Return a non-zero code from
mainto signal an error. - Check the return value of any function that can fail.
흔한 실수
- 오류를 알리기 위해
main에서 비영점(non-zero) 코드를 반환하세요. - 실패할 수 있는 모든 함수의 반환 값을 확인하십시오.
Now you try
- Return
0on success and-1on failure, and write the real answer through the out-pointer. - On failure, do not touch the out-pointer. Do not write a
main— the checker provides one.
이제 직접 해보기
- 성공 시
0를, 실패 시-1를 반환하고 실제 결과는 out-포인터를 통해 기록하십시오. - 실패 시 out-포인터를 건드리지 마십시오. 반드시
main를 작성하지 마십시오 — 체크기가 자동으로 그 값을 제공합니다.
Complete int safe_div(int a, int b, int *result): if b is 0, return -1 and leave *result alone. Otherwise store a / b in *result and return 0. Do not write a main. · int safe_div(int a, int b, int *result)를 완성하세요: b이 0인 경우, -1을 리턴하고 *result에는 손대지 마십시오. 그렇지 않으면 a / b을 *result에 저장한 후 0을 리턴하십시오. **main은 작성하지 마십시오.**
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Complete int parse_int(const char *s, int *out): if s is a valid integer (digits, with an optional leading -), store its value in *out and return 0; otherwise return -1. Do not write a main. · int parse_int(const char *s, int *out)를 완성하세요: s이 유효한 정수(숫자, 선행 - 가능)인 경우, 그 값을 *out에 저장하고 0을 리턴하십시오; 그렇지 않으면 -1을 리턴하십시오. **main은 작성하지 마십시오.**
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Complete int withdraw(int balance, int amount, int *new_balance): if amount is more than balance, return -1. Otherwise set *new_balance to balance - amount and return 0. Do not write a main. · int withdraw(int balance, int amount, int *new_balance)를 완성하세요: amount이 balance보다 크면 -1을 반환합니다. 그렇지 않으면 *new_balance에 balance - amount을 할당하고 0을 반환합니다. 반드시 main을 작성하지 마십시오.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.