How to catch the exception?

E

eas

How to catch the following exceptions?

Failure in an assignment operator
Detection of an out-of-bound index in a user-defined array
Range-checked access to a vector

Any comments are appreciated!
 
V

Victor Bazarov

eas said:
How to catch the following exceptions?

All exceptions are caught by a 'catch' clause after a 'try'
block in which the exception is thrown.
Failure in an assignment operator

What kind of "failure"?
Detection of an out-of-bound index in a user-defined array

No such standard exception, AFAIK. Consult your compiler manual
for a possible compiler-specific one.
Range-checked access to a vector

Do you mean std::vector or some other "vector"? If the standard
one, then there is no specific exception thrown on an attempt to
dereference an invalid iterator. There can be, of course, some
kind of implementation-specific one, but you'll have to look in
the compiler documentation for that.

Victor
 
R

Ron Natalie

eas said:
How to catch the following exceptions?

Failure in an assignment operator
Detection of an out-of-bound index in a user-defined array
Range-checked access to a vector

Any comments are appreciated!

operator[] on vector doesn't do any range checking.
vector::at does check and throw...

vector<int> v(10);

try {
v.at(12);
} catch (out_of_range) {
cerr << "You fool!\n";
}
 
K

Kevin Goodsell

eas said:
How to catch the following exceptions?

With a catch() block, as Victor said.
Failure in an assignment operator

Assignment operators are source-code constructs, which don't exist at
runtime. So I guess you mean a user-defined operator=(). In that case,
the function would have to throw an exception in order for it to be
caught, and you'd simply catch that exception as you would any other.
Detection of an out-of-bound index in a user-defined array

What do you mean by "user-defined array"? if you are talking about
built-in arrays, there's no standard exception that is thrown - an
out-of-bound access simply invokes undefined behavior.

If you defined an array class, you could check for out-of-bound accesses
and throw whatever exception you want. You would catch this the same way
you catch any other exception.
Range-checked access to a vector

If you use the vector::at() function, an exception will be thrown for an
out-of-range access, as Ron mentioned. operator[] silently invokes
undefined behavior on an out-of-range access.

In both the array and vector cases, you could feasibly create your own
range-checked iterators that throw an exception of your choice.

-Kevin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top