Usage of try and throw and catch statements in C++ programming exception handling

  • 2020-05-07 20:13:14
  • OfStack

To implement exception handling in C++, you can use try, throw, and catch expressions.
First, use the try block to close one or more statements that might throw an exception.
The throw expression signals that an exception condition (usually an error) has occurred in the try block. You can use any type of object as the operand of an throw expression. This object is commonly used to convey information about errors. In most cases, it is recommended that you use the std::exception class or one of the derived classes defined in the standard library. If one of these classes is not appropriate, it is recommended that you derive your own exception class from std::exception.
To handle exceptions that may be thrown, implement one or more catch blocks immediately after the try block. Each catch block specifies the type of exception it can handle.
The following example shows the try block and its handler. Suppose GetNetworkResource() gets the data over a network connection, and the two exception types are user-defined classes derived from std::exception. Note that the exception is caught by the const reference in the catch statement. We recommend that you throw an exception by value and catch it by constant reference.


MyData md;
try {
 // Code that could throw an exception
 md = GetNetworkResource();
}
catch (const networkIOException& e) {
 // Code that executes when an exception of type
 // networkIOException is thrown in the try block
 // ...
 // Log error message in the exception object
 cerr << e.what();
}
catch (const myDataFormatException& e) {
 // Code that handles another exception type
 // ...
 cerr << e.what();
}

// The following syntax shows a throw expression
MyData GetNetworkResource()
{
 // ...
 if (IOSuccess == false)
  throw networkIOException("Unable to connect");
 // ...
 if (readError)
  throw myDataFormatException("Format error"); 
 // ...
}

note
The code after the try clause is the protected part of the code. The throw expression raises (causes) an exception. The block of code after the catch clause is the exception handler. If the types in throw and catch expressions are compatible, the handler catches the exception that is thrown. For a list of rules that manage type matching in catch blocks, see how Catch blocks are calculated (C++). If the catch statement specifies the ellipsis (...) Instead of types, the catch block will handle each type of exception. When compiled using the /EHa option, exceptions can include C structured exceptions and system-generated or application-generated asynchronous exceptions, such as memory protection, zero division, and floating point conflicts. Because catch blocks are processed programmatically to find matching types, avoid using ellipsis handlers to process associated try blocks. Please use catch(...) with caution. ; Unless the catch block knows how to handle the specific exception caught, the program is not allowed to continue execution. catch (...). Block 1 is used to record errors and perform special cleanup before the program stops executing.
An throw expression with no operands rethrows the exception currently being processed. We recommend this form when an exception is rethrown because it preserves the polymorphic type information of the original exception. Such expressions should only be used in catch handlers or in functions called from catch handlers. The exception object that is rethrown is the original exception object, not a copy.


try {
 throw CSomeOtherException();
}
catch(...) {
 // Catch all exceptions  �  dangerous!!!
 // Respond (perhaps only partially) to the exception, then
 // re-throw to pass the exception to some other handler
 // ...
 throw;
}

Calculation method of Catch block (C++)
while it is generally recommended that you throw a type derived from std::exception, C++ enables you to throw any type of exception. You can catch an C++ exception by specifying an catch handler of the same type as the exception thrown, or by a handler that can catch any type of exception.
If the type of exception thrown is a class and it also has a base class (or class), it can be caught by a handler that accepts the base class of the exception type and a reference to the base of the exception type. Note that when an exception is caught by a reference, it is bound to the actual exception object that is thrown. Otherwise, it will be one copy (roughly the same as the function's arguments).
When an exception is thrown, it is caught by an catch handler of the following type:

Any type of handler can be accepted (using ellipsis syntax). Accepts the same type of handler as the exception object; Since it is a copy, the const and volatile modifiers are ignored. A handler that accepts a reference to the same type as the exception object. Accepts a handler for a reference to const or volatile of the same type as the exception object. A handler that accepts a base class of the same type as the exception object. Since it is a copy, the const and volatile modifiers are ignored. The catch handler for the base class must not precede the catch handler for the derived class. A handler that accepts a reference to a base class of the same type as the exception object. Handler that accepts a reference in the form const or volatile of the base class of the same type as the exception object. Accepts a handler that converts a raised pointer object to a pointer using standard pointer conversion rules.

The order in which the catch handlers appear makes sense because the handlers for a given try block are checked in the order in which they appear. For example, it is an error to place the handler of a base class before the handler of a derived class. After a matching catch handler is found, subsequent handlers are not checked. Therefore, the catch ellipsis handler must be the last handler of its try block. Such as:


// ...
try
{
 // ...
}
catch( ... )
{
 // Handle exception here.
}
// Error: the next two handlers are never examined.
catch( const char * str )
{
 cout << "Caught exception: " << str << endl;
}
catch( CExcptClass E )
{
 // Handle CExcptClass exception here.
}

In this example, the catch ellipsis handler is the only one handler checked.


Related articles: