Commit 71b234e2 authored by Administrator's avatar Administrator
Browse files

add exception handling

parent a1d084a7
#include <iostream>
using namespace std;
class MyException : public exception {
public:
const char * what () const throw () {
return "C++ Exception";
}
};
int main () {
double devident, devisor;
string buff;
cout << "Input devident:" << endl;
cin >> devident;
getline(cin, buff);
cout << "Input devisor:" << endl;
cin >> devisor;
getline(cin, buff);
// 显式地抛出异常
try {
if (devisor == 0) {
throw "Devisor can NOT be 0!";
}
cout << devident << " / " << devisor << " = " << devident/devisor << endl;
} catch (const char* msg) {
cout << msg << endl;
}
// 隐式地抛出异常
string s = "hello";
try {
char c = s.at(100); //拋出 out_of_range 异常
} catch (out_of_range & e) {
cout << e.what() << endl;
}
// 显式地抛出自定义异常
try {
throw MyException();
} catch (MyException& e) {
cout << e.what() << endl;
}
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment