SHAOXIAOJ正在加载中...

2382: 代码训练

金币值:1 定数:1 时间限制:1.000 s 内存限制:256 M
正确:0 提交:0 正确率:0.00% 命题人:
点赞量:0 收藏量:0 题目类型:程序

题目描述

[md] 练习代码,使用`DEV`编写代码操作 ```cpp #include using namespace std; int main(){ string str("abc"); // 从下标4开始取长度1的子串 // 函数会产生越界异常 str.substr(4,1); cout << "正常退出"; return 0; } ``` ```cpp // 抛出int类型的异常,并进行处理 #include using namespace std; int main(){ try{ throw 1; } catch(int e){ cout << "捕获异常" << endl; } return 0; } ``` ```cpp // 异常处理的例子 int main(){ int x; cin >> x; try { cout << "if判断前 \n"; if(x < 0){ cout << " 抛出异常 \n"; throw x; } cout << "if判断前后(如抛出异常则不会被执行) \n"; } catch(int x ) { cout << "捕获整数异常 \n"; } catch(exception e ) { cout << "捕获标准异常 \n"; } cout << "有无异常都会被执行 \n"; return 0; } ``` ```cpp //抛出的异常和任何catch中的类型都不匹配的例子 #include using namespace std; int main() { try { throw 'a'; } catch (int x) { cout << "捕获异常"; } cout << "正常退出"; return 0; } ``` ```cpp //catch(…)捕获所有类型异常的例子 #include using namespace std; int main() { try { throw 'a'; } catch (int x) { cout << "捕获异常"; } catch (...) { cout << "Default Exception\n"; } cout << "正常退出"; return 0; } ``` ```cpp // 对substr函数产生的标准异常进行异常处理的代码示例 #include #include #include using namespace std; int main(){ string str("abc"); try{ str.substr(4,1); } //catch(exception e){ catch(out_of_range e){ cout << "捕获异常:" << e.what() << endl; } cout << "正常退出"; return 0; } ``` ```cpp #include #include using namespace std; char get_char(const string &, int) throw(int); int main(){ string str = "c plus plus"; try{ cout << get_char(str, 2) << endl; cout << get_char(str, 100) << endl; }catch(int e){ if(e == 1){ cout << "Index underflow!" << endl; }else if(e == 2){ cout << "Index overflow!" << endl; } } return 0; } char get_char(const string &str, int index) throw(int){ int len = str.length(); if(index < 0) throw 1; if(index >= len) throw 2; return str[index]; } ``` ```cpp #include using namespace std; void function() throw (char){ throw 'F'; cout << 'T' << endl; } int main() { try { function(); } catch (char error) { cout << error << endl; } return 0; } ``` [/md]

输入格式

输出格式

提示