Dela via


Undantag: Fånga och ta bort undantag

Följande instruktioner och exempel visar hur du fångar och tar bort undantag. Mer information om nyckelorden try, catchoch throw finns i Moderna C++-metodtips för undantag och felhantering.

Undantagshanterarna måste ta bort undantagsobjekt som de hanterar, eftersom om undantaget inte tas bort uppstår en minnesläcka när koden fångar upp ett undantag.

Blocket catch måste ta bort ett undantag när:

  • Blocket catch genererar ett nytt undantag.

    Du får naturligtvis inte ta bort undantaget om du genererar samma undantag igen:

    catch (CException* e)
    {
       if (m_bThrowExceptionAgain)
          throw; // Do not delete e
       else
          e->Delete();
    }
    
  • Exekveringen återgår från inom catch blocket.

Anmärkning

När du tar bort en CExceptionanvänder du Delete medlemsfunktionen för att ta bort undantaget. Använd inte nyckelordet delete eftersom det kan misslyckas om undantaget inte finns på heap-minnet.

Så här fångar och tar du bort undantag

  1. Använd nyckelordet try för att konfigurera ett try block. Kör programinstruktioner som kan utlösa ett undantag i ett try block.

    Använd nyckelordet catch för att konfigurera ett catch block. Placera kod för undantagshantering i ett catch block. Koden i catch blocket körs endast om koden i try blocket genererar ett undantag av den typ som anges i -instruktionen catch .

    Följande skelett visar hur try och catch block normalt är ordnade:

    try
    {
       // Execute some code that might throw an exception.
       AfxThrowUserException();
    }
    catch (CException* e)
    {
       // Handle the exception here.
       // "e" contains information about the exception.
       e->Delete();
    }
    

    När ett undantag utlöses skickas kontrollen till det första catch blocket vars undantagsdeklaration matchar typen av undantag. Du kan selektivt hantera olika typer av undantag med sekventiella catch block enligt nedan:

    try
    {
       // Execute some code that might throw an exception.
       AfxThrowUserException();
    }
    catch (CMemoryException* e)
    {
       // Handle the out-of-memory exception here.
       e->Delete();
    }
    catch (CFileException* e)
    {
       // Handle the file exceptions here.
       e->Delete();
    }
    catch (CException* e)
    {
       // Handle all other types of exceptions here.
       e->Delete();
    }
    

Mer information finns i Undantag: Konvertera från MFC-undantagsmakron.

Se även

undantagshantering