void fileCopy(char* dst, char* src) {
if (src == NULL) {
throw 1;
}
if (dst == NULL) {
throw 2;
}
if (*src == 'a') {
throw 3;
}
while (*src != '\0') {
*dst = *src;
dst++;
src++;
}
*dst = '\0';
}
void fileCopy1(char* dst, char* src) {
if (src == NULL) {
throw "src error";
}
if (dst == NULL) {
throw "dst error";
}
if (*src == 'a') {
throw "cop error";
}
while (*src != '\0') {
*dst = *src;
dst++;
src++;
}
*dst = '\0';
}
class srcError {};
class dstError {};
class copyError {
public:
copyError() {
cout << "this is copyError()---" << endl;
}
copyError(const copyError &obj) {
cout << "this is copyError(const copyError &obj)---" << endl;
}
~copyError() {
cout << "this is ~copyError()---" << endl;
}
};
void fileCopy2(char* dst, char* src) {
if (src == NULL) {
throw srcError();
}
if (dst == NULL) {
throw dstError();
}
if (*src == 'a') {
//cout << "start test copyerror------------" << endl;
//throw copyError();
throw new copyError();
//throw& (copyError());1.this is copyError()2.this is ~copyError()------3.copy error----
}
while (*src != '\0') {
*dst = *src;
dst++;
src++;
}
*dst = '\0';
}
int main() {
int res = 0;
char src[] = "abcdefg";
char dst[1024] = { 0 };
try {
//fileCopy(dst,src);
//fileCopy1(dst, src);
fileCopy2(dst, src);
}
catch (int e) {
cout << "e: " << e << " int 类型异常....." << endl;
}
catch (char* e) {//由throw的常量char分配内存
cout << e << endl;
}
catch (srcError e) {
cout << "src error----" << endl;
}
catch (dstError e) {
cout << "dst error----" << endl;
}
//catch (copyError e) {//结论:使用异常变量则发生拷贝构造
// cout << "copy error----" << endl;
// //1.this is copyError()---2.this is copyError(const copyError &obj)---3.copy error
// //4.this is ~copyError()---5.this is ~copyError()---
//}
catch (copyError& e) {//变量引用和变量不能共存 即不屏蔽catch (copyError e) 报错 结论:使用引用时,引用值即为抛出值 即 copyError& e = throw copyError()
cout << "copy error----" << endl; //!!!!!推荐使用引用方式
//1.this is copyError()---2.copy error----3.this is ~copyError()---
}
catch (copyError* e) {//指针可以和变量,也可以和变量引用共存,但变量和变量引用不能共存
cout << "copy error----" << endl;
delete e;//如果不delete指针,不会发生析构
//1.this is copyError()---2.copy error----3.this is ~copyError()---
}
catch (...) {
cout << "未知类型异常......" << endl;
}
system("pause");
return 0;
}
06-26
543
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交