Re: Is default index acceptable?
On Sep 10, 4:33 am, Immortal Nephi <Immortal_Ne...@hotmail.com> wrote:
On Sep 9, 7:40 pm, Immortal Nephi <Immortal_Ne...@hotmail.com> wrote:
How do you prefer to use boolean if you don't want to=
use exception?
You can either choose this approach or insert exception into your
code.
If I go ahead to use this approach, I will turn off exc=
eption option
in C++ Compiler's setting for performance reason.
Please let me know if this code is acceptable.
class Obj {
=85
bool Set_At( int index, int value ) {
if ( 0 <= index && index < 4 ) {
m_data[ index ] = val=
ue;
return true;
}
return false;
}
int Get_At() const { return m_data; }
};
void test() {
if ( !_obj.Set_At( 4, 1234 ) )
cout << =93Catch error message!=94 << e=
ndl;
I want to add=85.
If you don't write an exception handler in your own, th=
en do
operating system triggers its own exception handler.
int main() {
int a[ 4 ];
a[ 5000 ] = 2; // Triggers unhandled exception
return 0;
}
The exception dialog displays the message =96
Unhandled exception at 0x00412c2e in Test.exe: 0xC0000005: Access
violation writing location 0x00134d74.
You need to distinguish this from a C++ language exception. This is
Windows-specific "structured exception" (SE). There is no such thing
on other operating systems. Code you have shown has a serious bug,
because accessing "a" after the end is undefined behavior (UB). And
indeed, SEs are most often, if not exclusively, caused by bugs in
code.
You should note that you need a particular compiler setting (MS
specific, look for /EHsc and /EHa) to be able to catch such an
exception, and even then, you can only catch(...), which is rather
bad.
If you ever feel you need to catch an SE, then:
1. think again (or, as I say to younger colleagues "you are not
allowed to write a catch")
2. use __try ... __except.
Situation you're describing is a clear-cut program bug (UB). That is
solved through a change in code first and foremost.
Goran.