What should one throw?, C/C++ Programming

A: C++, unlike only about every other language with exceptions, is extremely accomodating while it comes to what you can throw. Actually, you can throw anything you akin to. That begs the question then, what should you throw?

In general, it's best to throw objects, not built-ins. If achievable, you must throw instances of classes which derive (ultimately) from the std::exception class. Through making your exception class inherit (ultimately) from the standard exception base-class, you are making life simpler for users (they have the alternative of catching most things by std::exception), plus probably you are providing them with more information (as the fact that your particular exception might be a refinement of std::runtime_error or whatever).

The common practice is to throw temporary:

#include

class MyException : public std::runtime_error {

public:

MyException() : std::runtime_error("MyException") { }

};

void f()

{

// ...

throw MyException();

}

Here, a temporary of type MyException is created & thrown. Class MyException inherits from class std::runtime_error that (ultimately) inherits from class std::exception.

Posted Date: 3/19/2013 8:55:09 AM | Location : United States







Related Discussions:- What should one throw?, Assignment Help, Ask Question on What should one throw?, Get Answer, Expert's Help, What should one throw? Discussions

Write discussion on What should one throw?
Your posts are moderated
Related Questions

A PROGRAM TO CALCULATE AREA OF TRIANGLE

Sorted directory - C++ program: Write a program in c to sorting a directory. int main( int argc, char *argv[] ) {     if( argc 3 )         {         cerr

A:BinaryHeap.h ------------ #ifndef BINARY_HEAP_H_ #define BINARY_HEAP_H_ #include "dsexceptions.h" #include "vector.h" // BinaryHeap class // CONSTRUCTION: wi


Write a program that does the following: Calculates the Velocity and Momentum of an object. The formula for the velocity is V=d/t and the formula Momentum is m=mass*velocity. Your

write an algorithm that reads a postive integer n and then finds and prints the sum of all integers between 1 and n (inclusive) that are disvisible by 7. please write this using c

F u nction overloading: Functions can be defined with same name.  Depending upon the type of argument passed the function will perform.  This is known function overloading

how i can open a file

A: Something to let your class to grant access to another class or function. Friends may be either classes or functions. Class grants access privileges to its friends. In genera