C++中异常处理的基本思想及throw语句抛出异常的使用

2020-01-06 14:57:54于丽

异常接口声明
1)为了加强程序的可读性,可以在函数声明中列出可能抛出的所有异常类型,例如:
void func() throw (A, B, C , D); //这个函数func()能够且只能抛出类型A B C D及其子类型的异常。
2)如果在函数声明中没有包含异常接口声明,则次函数可以抛掷任何类型的异常,例如:
void func();
3)一个不抛掷任何类型异常的函数可以声明为:
void func() throw();
4) 如果一个函数抛出了它的异常接口声明所不允许抛出的异常,unexpected函数会被调用,该函数默认行为调用terminate函数中止程序。

传统处理错误


#include <iostream> 
#include <cstdio> 
using namespace std; 
 
// 传统的错误处理机制 
int myStrcpy(char *to, char *from) 
{ 
  if (from == NULL) { 
    return 1; 
  } 
  if (to == NULL) { 
    return 2; 
  } 
 
  // copy时的场景检查 
  if (*from == 'a') { 
    return 3; // copy时错误 
  } 
  while (*from != '') { 
    *to = *from; 
    to++; 
    from++; 
  } 
  *to = ''; 
 
  return 0; 
} 
 
int main() 
{ 
  int ret = 0; 
  char buf1[] = "zbcdefg"; 
  char buf2[1024] = { 0 }; 
 
  ret = myStrcpy(buf2, buf1); 
  if (ret != 0) { 
    switch (ret) { 
    case 1: 
      cout << "源buf出错!n"; 
      break; 
    case 2: 
      cout << "目的buf出错!n"; 
      break; 
    case 3: 
      cout << "copy过程出错!n"; 
      break; 
    default: 
      cout << "未知错误!n"; 
      break; 
    } 
  } 
  cout << "buf2:n" << buf2; 
  cout << endl; 
 
  return 0; 
} 

throw char*


#include <iostream> 
#include <cstdio> 
using namespace std; 
 
// throw char * 
void myStrcpy(char *to, char *from) 
{ 
  if (from == NULL) { 
    throw "源buf出错"; 
  } 
  if (to == NULL) { 
    throw "目的buf出错"; 
  } 
 
  // copy时的场景检查 
  if (*from == 'a') { 
    throw "copy过程出错"; // copy时错误 
  } 
  while (*from != '') { 
    *to = *from; 
    to++; 
    from++; 
  } 
  *to = ''; 
 
  return; 
} 
 
int main() 
{ 
  int ret = 0; 
  char buf1[] = "abcdefg"; 
  char buf2[1024] = { 0 }; 
 
  try 
  { 
    myStrcpy(buf2, buf1); 
  } 
  catch (int e) // e可以写可以不写 
  { 
    cout << e << "int类型异常" << endl; 
  } 
  catch (char *e) 
  { 
    cout << "char* 类型异常" << endl; 
  } 
  catch (...) 
  { 
  }; 
  cout << endl; 
 
  return 0; 
}