예외와 계약
Coddy의 GDScript 개발자를 위한 C++ 코스 레슨. 48개 중 28번째.
GDScript에는 예외가 없고 try/catch도 없습니다. 엔진 메서드는 Error 열거형이나 null 같은 반환값으로 실패를 알리고, 직접 작성한 함수도 같은 방식으로 동작할 수 있으며, error_string은 코드를 텍스트로 변환합니다. 런타임 스크립트 오류는 잡히지 않고 로그에 기록되며, assert는 디버그 빌드에서만 실행됩니다. 반면 C++에서는 형식이 지정된 예외를 던집니다. throw가 발생하면 일치하는 catch에 도달할 때까지 거치는 모든 함수에서 빠져나오고, 스택이 풀리면서 그 과정에서 생성된 자동 객체가 소멸합니다. Guard 같은 형식이 리소스를 해제하는 방식이 바로 이것입니다. 예상되는 예외 범주는 const 참조로 잡으세요.
GDScript
extends Node
func require_name(s: String) -> Error:
if s.is_empty():
return ERR_INVALID_PARAMETER
return OK
func _ready():
var err := require_name("")
if err != OK:
print("missing: ", error_string(err))
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Guard{~Guard(){std::cout<<"released\n";}};
void require_name(const std::string& s){Guard g;if(s.empty())throw std::invalid_argument("name");}
int main(){
try{require_name("");}catch(const std::invalid_argument& e){std::cout<<"missing "<<e.what()<<"\n";}
}
각 프로그램을 서로 독립적으로 추적해 보세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스 코드의 출력과 대상 코드의 출력이 일치한다고 가정하지 마세요.
챌린지
쉬움입력값은 분자와 제수입니다. 정수 몫을 반환하며, 0을 향해 버림합니다. 제수가 0이면 std::invalid_argument를 던집니다. 드라이버는 예외를 잡아 invalid를 출력합니다.
exercise.hpp와 exercise.cpp에 선언된 API를 구현하세요. 두 파일은 모두 편집할 수 있습니다. 공개 시그니처를 유지하세요. 잠긴 main.cpp는 stdin을 읽고 API를 직접 호출합니다. 명시된 경우 공개 API의 동작도 독립적으로 확인합니다. API 내부에서 출력하지 말고 반환값을 반환하세요. 정수 입력값과 결과는 부호 있는 int 범위에 들어갑니다. 별도로 명시되지 않는 한 텍스트는 ASCII입니다.
직접 해보기
#include "exercise.hpp"
#include <iostream>
int main(){
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int a,b;in>>a>>b;try{std::cout<<divide(a,b)<<"\n";}catch(const std::invalid_argument&){std::cout<<"invalid\n";}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
GDScript 개발자를 위한 C++의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러