Side question : Buy what if i use range error while working with vector and this vector is in try{} block, than something in vector library would throw exception right? Than i can catch it with catch{} right? |
If vector throws something, yes you can catch it in your catch block.
vector will throw a 'bad_alloc' exception if it fails to allocate memory, and vector::at will also throw an 'out_of_range' exception if you attempt to access an out of range element.
However accessing elements via the [] operator, and even via iterators will not throw any exception.
Also could someone tell me why isnt this good use |
You're basically only using it to escape a loop. It'd be better if you just made the 'exception' case the loop condition.
Exceptions should not be used as just a way to jump to another part of code. They're to be used when something has failed miserably.
In your case, nothing has failed. You simply reached the end of what you were trying to do. So exceptions are inappropriate here.
Also - i was thinking that i can probably throw anything instead of overflow_error("...") right? Like make emty class like class Overflow{}; and throw Overflow(); Would that make a difference (maybe 1 is safer than another?) |
You are correct. You can throw anything you want.
Though I find it's best to stick with standard exception classes where possible. For the same reason it's best to stick with standard container classes where possible: everyone is familiar with them and they're a common ground for all programmers.
Best of all, all standard exception classes are inherited from the std::exception base class, so this will catch practically every exception that could be thrown, AND it will tell you what went wrong:
1 2 3 4 5
|
try{ ... }
catch( std::exception& e )
{
cout << "This is what went wrong: " << e.what();
}
|
Child classes like overflow_error are further specialized so that you can have multiple catch block to handle different failure scenarios:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
try{ ... }
catch( std::overflow_error& e )
{
// had an overflow error
}
catch( std::bad_alloc& e )
{
// was unable to allocate enough memory
}
catch( std::out_of_range& e )
{
// tried to access something out of range
}
catch( std::exception& e )
{
// something else went wrong
}
|
As you might be able to see here, std::exception acts as a "catch all"... similar to the ellipsis:
catch(...)
. The difference is, the ellipsis does not give you any information about what was thrown, whereas with the std::exception class, you have an actual object that you can probe for information.
So yeah, my advice: either use the standard exception classes directly... or derive your own exception classes from them. Don't throw anything that doesn't ultimately derive from std::exception. Even though the language allows it, it isn't a good idea.