异常

异常和java一样,主要就是try catch

  1. try
  2. {
  3. // 保护代码
  4. }catch( ExceptionName e1 )
  5. {
  6. // catch 块
  7. }catch( ExceptionName e2 )
  8. {
  9. // catch 块
  10. }catch( ExceptionName eN )
  11. {
  12. // catch 块
  13. }

然后抛异常使用 throw

double division(int a, int b)
{
   if( b == 0 )
   {
      throw "Division by zero condition!";
   }
   return (a/b);
}

int main ()
{
   int x = 50;
   int y = 0;
   double z = 0;

   try {
     z = division(x, y);
     cout << z << endl;
   }catch (const char* msg) { //这里有意思,我们可以这样写
     cerr << msg << endl;
   }

   return 0;
}

定义的新异常

#include <iostream>
#include <exception>
using namespace std;

struct MyException : public exception
{
  const char * what () const throw ()
  {
    return "C++ Exception";
  }
};

int main()
{
  try
  {
    throw MyException();
  }
  catch(MyException& e)
  {
    std::cout << "MyException caught" << std::endl;
    std::cout << e.what() << std::endl;
  }
  catch(std::exception& e)
  {
    //其他的错误
  }
}
结果
MyException caught
C++ Exception

信号处理

信号 描述
SIGABRT 程序异常终止,调用abort
SIGFPE 错误的运算符,被除数为0溢出
SIGILL 检测非法指令
SIGINT 程序终止interrupt信号
SIGSEGV 非法访问内存
SIGTERM 发送到程序的终止请求

signal 函数

void (*signal (int sig, void (*func)(int)))(int);

其实就是注册信号,以及信号被触发后的回调函数

#include <iostream>
#include <csignal>
#include <unistd.h>

using namespace std;

void signalHandler( int signum )
{
    cout << "Interrupt signal (" << signum << ") received.\n";

    // 清理并关闭
    // 终止程序  

   exit(signum);  

}

int main ()
{
    // 注册信号 SIGINT 和信号处理程序
    signal(SIGINT, signalHandler);  

    while(1){
       cout << "Going to sleep...." << endl;
       sleep(1);
    }

    return 0;
}
结果
Going to sleep....
Going to sleep....
Going to sleep....
Interrupt signal (2) received.

raise() 函数

int raise (signal sig);

sig是要发送的信号编号,包括 SIGINT、SIGABRT、SIGFPE、SIGILL、SIGSEGV、SIGTERM、SIGHUP

#include <iostream>
#include <csignal>
#include <unistd.h>

using namespace std;

void signalHandler( int signum )
{
    cout << "Interrupt signal (" << signum << ") received.\n";

    // 清理并关闭
    // 终止程序 

   exit(signum);  

}

int main ()
{
    int i = 0;
    // 注册信号 SIGINT 和信号处理程序
    signal(SIGINT, signalHandler);  

    while(++i){
       cout << "Going to sleep...." << endl;
       if( i == 3 ){
          raise( SIGINT);
       }
       sleep(1);
    }

    return 0;
}
结果
Going to sleep....
Going to sleep....
Going to sleep....
Interrupt signal (2) received.