C++ Error Handling — Good Sources of Example Code?

前端 未结 4 609
甜味超标
甜味超标 2020-12-23 02:38

Just about every piece of example code everywhere omits error handling (because it \"confuses the issue\" that the example code is addressing). My programming knowledge come

4条回答
  •  梦毁少年i
    2020-12-23 02:57

    With C++, you should end up with less visible error handling code anyway, because you can leave a lot of the heavy lifting to Exceptions.

    In my opinion the most basic rule with exceptions (and one most commonly broken) is this. Don't try to catch exceptions unless you have a specific plan to handle them.

    With exceptions, you don't have to worry about error codes returned from functions, because well designed functions will just throw exceptions instead.

    In C a typical error handling scenario looks like this:

    int DoA() 
    {
     if (location == hellInAHandcart)
      return ERROR;
     else
      RETURN OK;
    }
    
    int DoB()
    {
      int err = DoA();
      if (err != OK)
         return err;
      else
         return DoSomethingElse1();
    }
    
    int DoC()
    {
      int err = DoB();
      if (err != OK)
         //Handle My error here in whatever way...
    }
    

    While in C++...

    void DoA() 
    {
     if (location == hellInAHandcart)
      throw Exception("Gone To Hell in a Handcart");
    }
    
    void DoB()
    {
      DoA();
      DoSomethingElse1();
    }
    
    void DoC()
    {
      try
      {
        DoB();
      }
      catch (Exception &E)
      {
        // Handle My error here in whatever way...
      }
    }
    

提交回复
热议问题