C++自定义异常类举个例子

2025-05-14 15:25:37
推荐回答(3个)
回答(1):

您好,废话不多说,上程序:#include
#include
#include
#include
using namespace std;

class Up {};
class Fit {};
void g();

void f(int i) throw (Up, Fit) {
switch(i) {
case 1: throw Up();
case 2: throw Fit();
}
g();
}

// void g() {} // Version 1
void g() { throw 47; } // Version 2
// (Can throw built-in types)

void my_unexpected() {
cout << "unexpected exception thrown";
exit(1);
}

int main() {
set_unexpected(my_unexpected);
// (ignores return value)
for(int i = 1; i <=3; i++)
try {
f(i);
} catch(Up) {
cout << "Up caught" << endl;
} catch(Fit) {
cout << "Fit caught" << endl;
}
}

回答(2):

废话不多说,上程序:#include
#include
#include
#include
using namespace std;

class Up {};
class Fit {};
void g();

void f(int i) throw (Up, Fit) {
switch(i) {
case 1: throw Up();
case 2: throw Fit();
}
g();
}

// void g() {} // Version 1
void g() { throw 47; } // Version 2
// (Can throw built-in types)

void my_unexpected() {
cout << "unexpected exception thrown";
exit(1);
}

int main() {
set_unexpected(my_unexpected);
// (ignores return value)
for(int i = 1; i <=3; i++)
try {
f(i);
} catch(Up) {
cout << "Up caught" << endl;
} catch(Fit) {
cout << "Fit caught" << endl;。

回答(3):

#include using namespace std;void main(){ int a=10; try{ for( a=10;a>0;a--) { if(a<3) throw exception("蛋疼"); cout< system("pause");}