异常与契约
Coddy 面向 Ruby 开发者的 C++ 课程的第 28 课,共 48 课。
Ruby 使用 raise 引发异常对象,按类选择 rescue 子句,并在异常沿调用栈向上传播时运行 ensure 代码,这也是带代码块的 File.open 会关闭文件的原因。C++ 没有 ensure 或 finally:C++ 的栈展开会改为调用析构函数。C++ 会抛出类型化异常,并在栈展开期间销毁已构造的自动对象。使用 const 引用捕获预期的异常类别。
Ruby
def with_guard
yield
ensure
puts "released"
end
begin
with_guard { Integer("bad") }
rescue ArgumentError
puts "invalid"
end
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";}
}
分别跟踪每个程序。这些示例使用与任务不同的操作或数据来演示这一概念,不假设源程序和目标程序的输出相同。
挑战
简单输入:被除数和除数。返回整数商,向零截断。当除数为零时,抛出 std::invalid_argument;驱动程序会捕获它并输出 invalid。
在 exercise.hpp 和 exercise.cpp 中实现已声明的 API。两个文件都可以编辑;请保留公开签名。已锁定的 main.cpp 会读取标准输入,并直接调用 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";}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 C++中的所有课
自己练习: C++ 在线编译器