Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
The following instructions and examples show you how to catch and delete exceptions. For more information on the try, catch, and throw keywords, see Modern C++ best practices for exceptions and error handling.
Your exception handlers must delete exception objects they handle, because failure to delete the exception causes a memory leak whenever that code catches an exception.
Your catch block must delete an exception when:
The
catchblock throws a new exception.Of course, you must not delete the exception if you throw the same exception again:
catch (CException* e) { if (m_bThrowExceptionAgain) throw; // Do not delete e else e->Delete(); }Execution returns from within the
catchblock.
Note
When deleting a CException, use the Delete member function to delete the exception. Do not use the delete keyword, because it can fail if the exception is not on the heap.
To catch and delete exceptions
Use the
trykeyword to set up atryblock. Execute any program statements that might throw an exception within atryblock.Use the
catchkeyword to set up acatchblock. Place exception-handling code in acatchblock. The code in thecatchblock is executed only if the code within thetryblock throws an exception of the type specified in thecatchstatement.The following skeleton shows how
tryandcatchblocks are normally arranged: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(); }When an exception is thrown, control passes to the first
catchblock whose exception-declaration matches the type of the exception. You can selectively handle different types of exceptions with sequentialcatchblocks as listed below: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(); }
For more information, see Exceptions: Converting from MFC Exception Macros.