The main example for try catch is something like this:
try {
Note that the three points are great for detecting all exceptions, although you don't know the βwhatβ you caught. This is why you should indicate the type in parentheses.
The exception to be caught can be any type starting with an int and ending with a pointer to an object that comes from the exception class. This concept is very flexible, but you should be aware of the exception that may occur.
This could be a more specific example using std :: excpetion: Note the catch by reference.
try { throw std::exception(); } catch (const std::exception& e) {
The following example assumes that you are writing C ++ with MFC libraries. It explains that a catch of CException is thrown, since a CFileException comes from CException. The CException object deletes itself if it is no longer needed. If your exception is not derived from CException, you should not throw a pointer and stick to the above example.
try { throw new CFileException(); } catch (CException* e) { // CFileException is caught }
Last but not least, it is also important: you can define several catch blocks to catch different exceptions:
try { throw new CFileException(); } catch (CMemoryException* e) { // ignore e } catch (CFileException* e) { // rethrow exception so it gets handeled else where throw; } catch (CException* e) { // note that catching the base class should be the last catch }
source share