Menu
CoddyTech

예외와 계약

Coddy의 JavaScript 개발자를 위한 C++ 코스 레슨. 48개 중 28번째.

JavaScript는 어떤 값이든 던질 수 있고, catch 블록은 모든 예외를 받으므로 특정 종류의 예외만 처리하려는 코드는 instanceof로 확인하고 나머지는 다시 던집니다. 정리 작업은 finally에 둡니다. C++는 형식이 지정된 예외를 던지고 형식에 따라 처리기를 선택하므로, catch (const std::invalid_argument&)는 해당 범주의 예외만 처리하고 다른 예외는 계속 전파됩니다. finally는 없습니다. 스택을 풀 때 C++는 생성된 모든 자동 객체를 소멸시키므로 정리 작업은 소멸자에 둡니다. 예상되는 예외 범주는 const 참조로 잡으세요.

JavaScript

function requireName(s) {
  try {
    if (s === "") throw new RangeError("name");
  } finally {
    console.log("released");
  }
}
try {
  requireName("");
} catch (err) {
  if (!(err instanceof RangeError)) throw err;
  console.log("invalid " + err.message);
}

C++

#include <iostream>
#include <stdexcept>
#include <string>

struct Guard {
    ~Guard() { std::cout << "released\n"; }
};

void requireName(const std::string& s) {
    Guard g;
    if (s.empty()) throw std::invalid_argument("name");
}

int main() {
    try {
        requireName("");
    } catch (const std::invalid_argument& e) {
        std::cout << "invalid " << e.what() << "\n";
    }
}

각 프로그램의 실행 과정을 각각 추적하세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 원본 출력과 대상 출력이 일치한다고 가정하지 마세요.

challenge icon

챌린지

쉬움

입력: 피제수와 제수. 정수 몫을 반환하며, 0을 향해 버림합니다. 제수가 0이면 std::invalid_argument를 던지고, 드라이버가 이를 잡아 invalid를 출력합니다.

exercise.hpp와 exercise.cpp에 선언된 API를 구현하세요. 두 파일 모두 편집할 수 있으며, 공개 시그니처를 보존하세요. 잠금된 main.cpp는 표준 입력을 읽고 API를 직접 호출합니다. 또한 명시된 경우 공개 API의 동작을 별도로 확인합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력값과 결과는 signed 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";}
}
quiz icon실력 점검

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

JavaScript 개발자를 위한 C++의 모든 레슨

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