Accepted exceptions :: Beforehand Barring administration
| |
Standard exceptions
The set of exceptions acclimated with the Accepted C++ library is aswell accessible for your use. About its easier and faster to alpha with a accepted barring chic than to try to ascertain your own. If the accepted chic doesnt do absolutely what you need, you can acquire from it.
All accepted barring classes acquire ultimately from the chic exception, authentic in the attack <exception>. The two capital acquired classes are logic_error and runtime_error, which are begin in <stdexcept> (which itself includes <exception>). The chic logic_error represents errors in programming logic, such as casual an invalid argument. Runtime errors are those that action as the aftereffect of abrupt armament such as accouterments abortion or anamnesis exhaustion. Both runtime_error and logic_error accommodate a architect that takes a std::string altercation so that you can abundance a bulletin in the barring item and abstract it after with exception::what( ), as the afterward program illustrates.
// Derives an barring chic from std::runtime_error
#include <stdexcept>
#include <iostream>
using namespace std;
class MyError : accessible runtime_error {
public:
MyError(const string& msg = "") : runtime_error(msg) {}
};
int main() {
try {
throw MyError("my message");
}
catch (MyError& x) {
cout << x.what() << endl;
}
} ///:~
Although the runtime_error architect passes the bulletin up to its std::exception subobject to hold, std::exception does not accommodate a architect that takes a std::string argument. Therefore, you usually wish to acquire your barring classes from either runtime_error or logic_error (or one of their derivatives), and not from std::exception.
| exception | The abject chic for all the exceptions befuddled by the C++ accepted library. You can ask what( ) and retrieve the alternative cord with which the barring was initialized. |
|---|---|
| logic_error | Derived from exception. Letters program argumentation errors, which could apparently be detected by inspection. |
| runtime_error | Derived from exception. Letters runtime errors, which can apparently be detected alone if the program executes. |
Exception specifications
Youre not appropriate to acquaint the humans using your action what exceptions you ability throw. Abortion to do so can be advised uncivilized, however, because it agency that users cannot be abiding what cipher to address to bolt all abeyant exceptions. Of course, if they accept your antecedent code, they can coursing through and attending for bandy statements, but generally a library doesnt appear with sources. Acceptable affidavit can advice allay this problem, but how some software projects are able-bodied documented? C++ provides syntax that allows you to acquaint the user what exceptions this action throws, so the user can handle them. This is the alternative barring specification, which adorns a functions declaration, actualization afterwards the altercation list.
The barring blueprint reuses the keyword throw, followed by a parenthesized account of all the types of abeyant exceptions that the action can throw. Your action acknowledgment ability attending like this:
void f() throw(toobig, toosmall, divzero);
As far as exceptions are concerned, the acceptable action declaration
void f();
means that any blazon of barring can be befuddled from the function. If you say
void f() throw();
no exceptions whatsoever will be befuddled from the action (so youd bigger be abiding that no functions further down in the alarm alternation let any exceptions bear up!).
For acceptable coding policy, acceptable documentation, and ease-of-use for the action caller, consistently accede using barring blueprint if you address functions that bandy exceptions.
The unexpected( ) function
If your barring blueprint claims youre traveling to bandy a assertive set of exceptions and then you bandy something that isnt in that set, whats the penalty? The appropriate action unexpected( ) is alleged if you bandy something additional than what appears in the barring specification. Should this adverse bearings occur, the absence accomplishing of abrupt calls the terminate( ) action mentioned beforehand in this chapter.
The set_unexpected( ) function
Like terminate( ), the unexpected( ) apparatus allows you to install your own action to acknowledge to abrupt exceptions. You do so with a action alleged set_unexpected( ), which, like set_terminate( ), takes the abode of a action with no arguments and abandoned acknowledgment value. Also, because it allotment the antecedent amount of the unexpected( ) pointer, you can save it and restore it later. To use set_unexpected( ), you haveto cover the attack book <exception>. Heres an archetype that shows a simple use of the appearance discussed so far in this section:
// Barring blueprint & unexpected()
//{-msc} Doesnt abolish properly
#include <exception>
#include <iostream>
#include <cstdlib>
using namespace std;
class Up {};
class Fit {};
void g();
void f(int i) bandy (Up, Fit) {
switch(i) {
case 1: bandy Up();
case 2: bandy Fit();
}
g();
}
// abandoned g() {} // Adaptation 1
void g() { bandy 47; } // Adaptation 2
void my_unexpected() {
cout << "unexpected barring thrown" << endl;
exit(0);
}
int main() {
set_unexpected(my_unexpected);
// (ignores acknowledgment value)
for(int i = 1; i <=3; i++)
try {
f(i);
} catch(Up) {
cout << "Up caught" << endl;
} catch(Fit) {
cout << "Fit caught" << endl;
}
} ///:~
The classes Up and Fit are created alone to bandy as exceptions. Generally barring classes will be small, but they can absolutely authority added advice so that the handlers can concern for it.
The f( ) action promises in its barring blueprint to bandy alone exceptions of blazon Up and Fit, and from searching at the action definition, this seems plausible. Adaptation one of g( ), alleged by f( ), doesnt bandy any exceptions, so this is true. But if anyone changes g( ) so that it throws a altered blazon of barring (like the additional adaptation in this example, which throws an int), the barring blueprint for f( ) is violated.
The my_unexpected( ) action has no arguments or acknowledgment value, afterward the able anatomy for a custom unexpected( ) function. It artlessly displays a bulletin so that you can see that it has been alleged and then exits the program (exit(0) is acclimated actuality so that the books create action is not aborted). Your new unexpected( ) action should not accept a acknowledgment statement.
In main( ), the try block is aural a for loop, so all the possibilities are exercised. In this way, you can accomplish something like resumption. Backup the try block central a for, while, do, or if and couldcause any exceptions to attack to adjustment the problem; then attack the try block again.
Only the Up and Fit exceptions are bent because those are the alone exceptions that the programmer of f( ) said would be thrown. Adaptation two of g( ) causes my_unexpected( ) to be alleged because f( ) then throws an int.
In the alarm to set_unexpected( ), the acknowledgment amount is ignored, but it can aswell be adored in a arrow to action and be adequate later, as we did in the set_terminate( ) archetype beforehand in this chapter.
A archetypal abrupt abettor logs the absurdity and terminates the program by calling exit( ). It can, however, bandy addition barring (or re-throw the aforementioned exception) or alarm abort( ). If it throws an barring of a blazon accustomed by the action whose blueprint was originally violated, the seek resumes at the alarm of the action with this barring specification. (This behavior is different to unexpected( ).)
If the barring befuddled from your abrupt abettor is not accustomed by the aboriginal functions specification, one of the afterward occurs:
- If std::bad_exception (defined in <exception>) was in the functions barring specification, the barring befuddled from the abrupt abettor is replaced with a std::bad_exception object, and the seek resumes from the action as before.
- If the aboriginal functions blueprint did not cover std::bad_exception, terminate( ) is called.
The afterward program illustrates this behavior.
#include <exception> // for std::bad_exception
#include <iostream>
#include <cstdio>
using namespace std;
// Barring classes:
class A {};
class B {};
// terminate() handler
void my_thandler() {
cout << "terminate called
";
exit(0);
}
// unexpected() handlers
void my_uhandler1() {
throw A();
}
void my_uhandler2() {
throw;
}
// If we bury this bandy account in f or g,
// the compiler Interface' onMouseOver="tip('infobox6')" onMouseOut="untip()" target='_parent'> compiler Interface' onMouseOver="tip('infobox7')" onMouseOut="untip()" target='_parent'> compiler Interface' onMouseOver="tip('infobox6')" onMouseOut="untip()" target='_parent'> compiler Interface' onMouseOver="tip('infobox7')" onMouseOut="untip()" target='_parent'> compiler detects the abuse and reports
// an error, so we put it in its own function.
void t() {
throw B();
}
void f() throw(A) {
t();
}
void g() throw(A, bad_exception) {
t();
}
int main() {
set_terminate(my_thandler);
set_unexpected(my_uhandler1);
try {
f();
}
catch (A&) {
cout << "caught an A from f
";
}
set_unexpected(my_uhandler2);
try {
g();
}
catch (bad_exception&) {
cout << "caught a bad_exception from g
";
}
try {
f();
}
catch (...) {
cout << "This will never print
";
}
} ///:~
The my_uhandler1( ) abettor throws an adequate barring (A), so beheading resumes at the first catch, which succeeds. The my_uhandler2( ) abettor does not bandy a accurate barring (B), but back g specifies bad_exception, the B barring is replaced by a bad_exception object, and the additional bolt aswell succeeds. Back f does not cover bad_exception in its specification, my_thandler( ) is alleged as a abolish handler. Thus, the achievement from this program is as follows:
caught an A from f
caught a bad_exception from g
terminate called
Typical uses of exceptions
Do use exceptions to do the following:
- Fix the problem and alarm the action which acquired the barring again.
- Patch things up and abide after retrying the function.
- Do whatever you can in the accepted ambience and rethrow the aforementioned barring to a college context.
- Do whatever you can in the accepted ambience and bandy a altered barring to a college context.
- Terminate the program.
- Wrap functions (especially C library functions) that use accustomed absurdity schemes so they aftermath exceptions instead.
- Simplify. If your barring arrangement makes things added complicated, it is aching and annoying to use.
- Make your library and program safer. This is a concise investment (for debugging) and a abiding investment (for appliance robustness).
When to use barring specifications
The barring blueprint is like a action prototype: it tells the user to address exception-handling cipher and what exceptions to handle. It tells the compiler Interface' onMouseOver="tip('infobox6')" onMouseOut="untip()" target='_parent'> compiler Interface' onMouseOver="tip('infobox7')" onMouseOut="untip()" target='_parent'> compiler Interface' onMouseOver="tip('infobox6')" onMouseOut="untip()" target='_parent'> compiler Interface' onMouseOver="tip('infobox7')" onMouseOut="untip()" target='_parent'> compiler the exceptions that ability appear out of this action so that it can ascertain violations at runtime.
Of course, you deceit consistently attending at the cipher and ahead which exceptions will appear from a accurate function. Sometimes, the functions it calls aftermath an abrupt exception, and sometimes an old action that didnt th
|
exception, function, unexpected, exceptions, throw, error, specification, terminate, runtime, class, program, functions, standard, {cout, thrown, logic, called, handler, throws, classes, caught, exception>, catch, value, library, following, version, return, context, }catch, message, argument, errors, {throw, derive, block, resumes, thandler, handling, uhandler2, }void, uhandler1, example, takes, namespace, problem, myerror, write, iostream>, later, reports, string, object, constructor, , < <, exception specification, {cout <, runtime error, < exception>, std exception, exception classes, logic error, return value, std bad, thrown from, < endl, exception thrown, unexpected function, unexpected handler, error and, exception object, object and, namespace std, < iostream>, exceptions that, exception handling, < iostream> include, errorderived from exception, }int main {set, exception thrown from, original functions specification, following program illustrates, std string argument, exceptions advance exception, advance exception handling, exception handling standard, constructor that takes, standard exceptions advance, |
Also see ...
Catching an exception/H1PAs mentioned earlier, one of the advantages of C++ barring administration is that it allows you to apply on the problem youre infact aggravating to break in one place, and then accord with the errors from that cipher in addition place. /P
Catching an exception/H1PAs mentioned earlier, one of the advantages of C++ barring administration is that it allows you to apply on the problem youre infact aggravating to break in one place, and then accord with the errors from that cipher in addition place. /P
Catching an exception/H1PAs mentioned earlier, one of the advantages of C++ barring administration is that it allows you to apply on the problem youre infact aggravating to break in one place, and then accord with the errors from that cipher in addition place. /P
Catching an exception/H1PAs mentioned earlier, one of the advantages of C++ barring administration is that it allows you to apply on the problem youre infact aggravating to break in one place, and then accord with the errors from that cipher in addition place. /P
Catching an exception/H1PAs mentioned earlier, one of the advantages of C++ barring administration is that it allows you to apply on the problem youre infact aggravating to break in one place, and then accord with the errors from that cipher in addition place. /P
Throwing an exception/H1PIf you appointment an aberrant bearings in your codethat is, one in which you dont accept abundant advice in the accepted ambience to adjudge what to doyou can forward advice about the absurdity into a beyond ambience by creating an item that cont
Throwing an exception/H1PIf you appointment an aberrant bearings in your codethat is, one in which you dont accept abundant advice in the accepted ambience to adjudge what to doyou can forward advice about the absurdity into a beyond ambience by creating an item that cont
Throwing an exception/H1PIf you appointment an aberrant bearings in your codethat is, one in which you dont accept abundant advice in the accepted ambience to adjudge what to doyou can forward advice about the absurdity into a beyond ambience by creating an item that cont
Throwing an exception/H1PIf you appointment an aberrant bearings in your codethat is, one in which you dont accept abundant advice in the accepted ambience to adjudge what to doyou can forward advice about the absurdity into a beyond ambience by creating an item that cont
Throwing an exception/H1PIf you appointment an aberrant bearings in your codethat is, one in which you dont accept abundant advice in the accepted ambience to adjudge what to doyou can forward advice about the absurdity into a beyond ambience by creating an item that cont