文件(Files)与异常(Exceptions)
文件(Files)
- 可以使用
fstream库处理文件
#include <iostream>
#include <fstream>
fstream库中包含三个类,用于创建,写入和读取文件:
| 类名 | 描述 |
|---|---|
| ofstream | 创建和写入文件 |
| ifstream | 从文件读取 |
| fstream | 前两个类的组合 |
异常(Exceptions)
关键字
try throw catch
try定义要执行的代码块,会返回错误catch定义如果在try块中发生错误时,则执行的代码块。throw关键字抛出异常,允许创建一个自定义的错误
eg.
int main () try
{
int a = 5;
int b = 0;
double c = 0.0;
if(b == 0){
throw "denominator cannot be zero!";
}
else {
c = a / b;
cout <<"a / b = "<< c << endl;
}
return 0;
}
catch (const char* msg)
{
cerr << msg << endl;
}
因为抛出了一个类型为 const char* 的异常,想要捕获该异常,就必须在 catch 中使用 const char*,如果上例代码编译并执行,则会产生如下结果
denominator cannot be zero!
C++标准的异常
- C++ 提供了一系列标准的异常,定义在
exception类中 - 可以通过继承和重载 exception 类来定义新的异常
eg.
#include <iostream>
#include <exception>
struct MyException :public exception
{
const char * what () const throw () {
return "my custom exception";
}
};
int main()
{
try {
throw MyException();
}
catch(MyException& e) {
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
}
catch(std::exception& e) {
//其他的错误
}
}
关于异常规范的修改
C++11 提供了一种语法,可用于指出那些函数可能引发哪些异常
void f501(int) throw(bad_dog); // 可能抛出 bad_dog 异常
void f733(long long) throw(); // 不会抛出异常
标准委员会认为,指出函数不会引发异常有一定的价值,为此添加了关键字 noexcept
void f875(short, short) noexcept; // 不会抛出异常