📄 21-1.txt
字号:
/* 范例:21-1 使用try,catch */
#include <string.h>
#include <iostream.h>
void main()
{
string str1;
try
{
str1 = "SCA";
/*cout << str1.substr(0); /* 将字符串由0开始输出,所以会输出:
SCA */
/*cout << str1.substr(1,2); /* 将字符串由S开始输出, 只输出两个,所以输出SC */
cout << str1.substr(4); // 这将会产生例外,这超过字符串长度。
cout << "这个语句永远不会被读到且输出,因为上面已送出例外!!";
}
catch(logic_error e) /* 这个例外是C++提供的标准错误类,这边也可以使用
out_of_range这是继承logic_error, 而这次的超过字符串
长度是归类于logic_error下的out_of_range */
{
cout << "把 Out_of_range error输出到屏幕上:" << e.what() << endl;
}
getchar();
}
程序执行结果:
(会迸出以下这个警告:)
project p21-1.exe raised exception class std::out_of_range with message 'Exception Object Address:0x68303E'. Process stopped. Use Step or Run to continue.
(当看到这信息后,再编译一次结果如下﹕)
Throw Out_of_range error:position beyond end of string in function: basic_string
::substr(size_t,size_t) const
index: 4 is greater than max_index: 3
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -