In: Computer Science
C++ problem
1) Describe briefly what exceptions are and what their purpose
is. What is the try block? What is the catch block? What happens
with the flow of control if the catch block does not catch a thrown
exception? Give a simple example.
2) Describe briefly what templates are and what their purpose
is.
Answer:
1)Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw.
A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.
catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
If it does not catch clause that matches a supertype for the exception, then the exception is propagated down the call stack
2)
Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.
A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms are examples of generic programming and have been developed using template concept.
There is a single definition of each container, such as vector, but we can define many different kinds of vectors for example, vector <int> or vector <string>.
The general form of a template function definition is shown here:
template <class type> ret-type func-name(parameter list) {
// body of function
}
Here, type is a placeholder name for a data type used by the function. This name can be used within the function definition.