CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 18
  1. #1
    Join Date
    Nov 2006
    Location
    Barcelona - Catalonia
    Posts
    364

    Exception Handling

    Hi,
    I'm having many problems working with exception, which I'm not used to.
    First of all, does anybody know a good tutorial, manual, whatever,.... about'em? It'd be wondelfull if it was in Spanish , but in English will be enough too.

    I've made a very simple program to catch and exception, and I don't know why it's not cached:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>

    int main(void)
    {
    char *a = NULL;
    try{
    printf("Reservem\n");
    a = new char[20];
    printf("Incialitzem\n");
    memset(a, 0x00, 2000);
    printf("Accedim a 200\n");
    a[200] = '2';
    printf("Borrem\n");
    delete []a;
    printf("Sortim\n");
    }
    catch(...){
    printf("Exception captured\n");
    delete []a;
    exit(EXIT_FAILURE);
    }

    return 0;
    }

    It's compiled with GNU GCC:
    g++ -Wall -fexceptions -o prova.exe prova.cpp

    I don't know why I can't catch the exception (I think I should)?

    Thanks a lot, and sorry for my english.

    Albert.

  2. #2
    Join Date
    Dec 2004
    Location
    Poland
    Posts
    1,165

    Re: Exception Handling

    You cannot catch your exception, because it is not C++ exception. It is Access Violation error raised by CPU and it has nothing in common with C++ and C++ exception handling. To catch CPU exceptions, you need to use platform-dependant system-specific stuff, like SEH for Windows. C++ exceptions work kinda like this:
    Code:
    //create vector with 20 elements
    vector<int>vec(20);
    try {
       //access out of range with at member function, it is described by
       //standard as throwing out_of_range when invalid range is
       //passed
       int num = vec.at(200);
    } catch (out_of_range ex) {
       cout << ex.what(); //print a message
    }
    Generally, every function which might throw some an exception should be documented so, so you could know what to catch.

    Cheers,
    Hob

    EDIT oops, i messed up the exception class name...
    Last edited by Hobson; November 10th, 2006 at 07:31 AM.
    B+!
    'There is no cat' - A. Einstein

    Use &#91;code] [/code] tags!

    Did YOU share your photo with us at CG Members photo gallery ?

  3. #3
    Join Date
    Feb 2005
    Location
    Normandy in France
    Posts
    4,590

    Re: Exception Handling

    Your program has undefined behavior because it accesses a memory block out of its bounds.
    Undefined behavior means that the standard specifies nothing about the behavior (even though your compiler is allowed to document a particular behavior) of your program.
    It might play the 9th symphony of Beethoven or make daemons fly out of your nose.
    It might raise sometimes a SIGSEGV OS-level signal on UNIX systems, and sometimes do nothing particular.
    It might behave as if the array was larger.
    It might throw an exception, though most compilers won't do it.

    You seem to confuse three things:
    • software exceptions.
      These exceptions are all thrown explicitly with throw() or thrown by standard library functions such as the default operator new (throws std::bad_alloc if there is not enough memory) or std::vector::at().
      Those exceptions are reliable.
    • OS signals.
      These are signals that a few OS on a few protected mode CPU (not all CPU) may raise when a division by zero is done, an illegal instruction is executed, or a memory page is accessed while it's not mapped to virtual memory (only for systems having pagined memory) or the software has not the correct access rights to read or write to this page.

      A few of thems can be reliable (but non-portable) on specific systems.
      For example, the standard doesn't require that a division by zero be detected and handled by a signal routine (since behavior is undefined, everything is allowed), but implementations are allowed to handle it and it's reliable on a few systems such as a number of compilers under Win32.

      A page fault can be reliably raised on some systems too.... However you must not expect that any access out of bounds of an array will raise a page fault! Most of those accesses don't!
      Because:
      • You array might happen to be contiguous to an allocated piece of memory... For example, another variable of your program!
      • Free memory pages are not required to be immediately unmapped from memory by the compiler's allocator.
      • Memory pages have a granularity (4096 bytes on Win32 i386 systems).
    • Undefined behavior.
      Most of the undefined behaviors are never tracked by software or OS level signals or exceptions... It's only expressed either as the expected behavior or as a weird behavior that happens at distance of the faulty instruction.
    "inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
    Club of lovers of the C++ typecasts cute syntax: Only recorded member.

    Out of memory happens! Handle it properly!
    Say no to g_new()!

  4. #4
    Join Date
    Jun 2004
    Location
    India
    Posts
    432

    Re: Exception Handling

    The catch(...) can catch memory access violation such as in your code or e.g. NULL pointer accedd. Granted that a NULL pointer access exception is raiased by hardware, caught by OS and then the processing is dependant on the OS. It is not C++ exception. But atleast on Windows, the OS would pass on that exception to your program and if you have a catch(...) handler then it will catch that. There may be various ways to tell the compiler to catch those exceptions.

    A memory overwrite beyond array location may or may not generate access violation.

    1. In many cases it would not - if the memory beyond the array boundary is allocated by your program, and is 'writeable', then you can happily write to that location and CPU would not complain.
    2. The problem comes when the memory beyond the buffer, that your program attempts to write, is not allocated by your program. Then most certainly the program would get a memory access violation and your catch(...) will catch it (depending on your compiler settings).
    Say no to supplying ready made code for homework/work assignments!!

    Please rate this post!

  5. #5
    Join Date
    Feb 2005
    Location
    Normandy in France
    Posts
    4,590

    Re: Exception Handling

    Quote Originally Posted by UnderDog
    But atleast on Windows, the OS would pass on that exception to your program and if you have a catch(...) handler then it will catch that.
    This statement is generally false. I think it applies to only a very small set of Windows compilers (mainly Visual C++ compilers).
    "inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
    Club of lovers of the C++ typecasts cute syntax: Only recorded member.

    Out of memory happens! Handle it properly!
    Say no to g_new()!

  6. #6
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    Re: Exception Handling

    Java throws exceptions whenever bounds are exceeded because Java performs bounds-checking.

    Whilst this is safer, it is also slower (although with the new foreach equivalent, you can iterate through a collection without using any indexing and this would be optimal).

    In C++ the general concept is that exceptions are thrown due to run-time conditions beyond the programmer's control, not to catch bugs in his program. Bugs should not exist in the first place. There are tools for trapping bugs.

    But then Java is often more of a "write and use now" language whereas C++ is more of a language for writing applications that you are going to export.

  7. #7
    Join Date
    Nov 2006
    Location
    Barcelona - Catalonia
    Posts
    364

    Re: Exception Handling

    I think I've undestood some things which I was totally confused. I thought I could catch almost everything with 'catch(...)'.
    About the platform: I usually work with VC++ 6.0 without MFC, but I also work with the GNU compiler, which I think I should be better, but more difficult to use in large projects. And the applications runs over an XP or W2000/3.

    So, do you know a good place, article, book, to undestand how to handle exceptions in C/C++ deeply? Because almost all books I've read, only says a few words about that.

    Thanks a lot for your help.

    Albert.

  8. #8
    Join Date
    Jun 2004
    Location
    India
    Posts
    432

    Re: Exception Handling

    Quote Originally Posted by SuperKoko
    This statement is generally false. I think it applies to only a very small set of Windows compilers (mainly Visual C++ compilers).
    I agree that the compiler implementation of handling those exceptions will vary. But I also think that most C++ compiler targetted for windows should be implementing it. The part about OS passing that exception to the program is not compiler dependant.

    If a particular compiler is not producing code to catch hardware exceptions, then one can code some OS exception handlers to catch those exceptions and generate C++ exceptions out of them.
    Say no to supplying ready made code for homework/work assignments!!

    Please rate this post!

  9. #9
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

  10. #10
    Join Date
    Nov 2006
    Location
    Barcelona - Catalonia
    Posts
    364

    Re: Exception Handling

    To catch ACCESS_VIOLATION exceptions I've found this function provided by VC++: _set_se_translator. MSDN tells me that it's used to "Handles Win32 exceptions (C structured exceptions) as C++ typed exceptions". What does it mean? In other words, What's de difference between C and C++ exceptions?
    I didn't try but, Will this funtion catch the access out of bounds?
    Thanks.

    Albert.

  11. #11
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

    Re: Exception Handling

    Quote Originally Posted by AlbertGM
    To catch ACCESS_VIOLATION exceptions I've found this function provided by VC++: _set_se_translator. MSDN tells me that it's used to "Handles Win32 exceptions (C structured exceptions) as C++ typed exceptions". What does it mean? In other words, What's de difference between C and C++ exceptions?
    I didn't try but, Will this funtion catch the access out of bounds?
    Thanks.

    Albert.
    The point is you should be avoiding such issues at compile time. You need not catch exceptions for these. These are programming errors that should be fixed at compile time during development. Even if there are platform dependent routines that exist, you should not be relying on them or using them.

  12. #12
    Join Date
    Feb 2005
    Location
    Normandy in France
    Posts
    4,590

    Re: Exception Handling

    Quote Originally Posted by UnderDog
    But I also think that most C++ compiler targetted for windows should be implementing it. The part about OS passing that exception to the program is not compiler dependant.
    They should perhaps, but most don't. So, IMHO, you should not rely on it either.
    In fact, the only compiler I know that transform OS exceptions into software exceptions is Visual C++.

    I've just tested:

    Borland C++ 5.5
    GCC (MinGW 3.4.5)
    Digital Mars Compiler 8.42
    Salford SCC 3.64
    OpenWatcom 1.3
    cint 5.15

    None of them translate OS exceptions to software exceptions.
    All of them crash for a statement such as *((int*)0)=42; in a try block.

    Salford SCC displays a pretty detailed crash dump, though.

    If a particular compiler is not producing code to catch hardware exceptions, then one can code some OS exception handlers to catch those exceptions and generate C++ exceptions out of them.
    I think it applies to most Win32 compilers... Except Visual C++.
    Last edited by SuperKoko; November 13th, 2006 at 03:19 PM.
    "inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
    Club of lovers of the C++ typecasts cute syntax: Only recorded member.

    Out of memory happens! Handle it properly!
    Say no to g_new()!

  13. #13
    Join Date
    Nov 2002
    Location
    Foggy California
    Posts
    1,245

    Re: Exception Handling

    Quote Originally Posted by SuperKoko
    Undefined behavior means that the standard specifies nothing about the behavior (even though your compiler is allowed to document a particular behavior) of your program.
    It might play the 9th symphony of Beethoven or make daemons fly out of your nose.
    Why does it have to be my nose demons fly out of? Why can't it be the developer's nose who wrote the offending code? I'm going to contact Bjarne, Herb, P.J., and the rest of the standards comittee and demand that they make this change in C++0x!
    Kevin Hall

  14. #14
    Join Date
    Feb 2005
    Location
    Normandy in France
    Posts
    4,590

    Re: Exception Handling

    Quote Originally Posted by KevinHall
    Why does it have to be my nose demons fly out of? Why can't it be the developer's nose who wrote the offending code? I'm going to contact Bjarne, Herb, P.J., and the rest of the standards comittee and demand that they make this change in C++0x!
    The standard doesn't forbid it. This sort of thing has to be forbidden by the law of your country. Forbidding such thing is not the job of the C++ committee.
    If daemons run out of your nose, you should not contact Bjarne & other committee members, because this is not their matter... You should contact your compiler vendor (if you can prove that it's due to the compiler and not your hardware) because it breaks other american laws... But the ISO/IEC 14882 doesn't contain the whole american law (or laws of other countries... Knowing that they would be all incompatible).
    Similarly, if your computer explode at your face, you should not contact Bjarne... You should complain at your computer vendor, and the problem will be traced up to the responsible hardware component, and, for example, if you can prove that a bomb has been volountary put into it, you can exhibit a law of your country that forbids that (it would probably be punished as terrorism).

    The standard does specify what is a C++ implementation, nothing more. It doesn't say if you must vaccinate your dog!

    Similarly, if the standard was a document containing these simple words:
    "Anything on the earth is a C++ implementation"
    You would not accuse the C++ standard of all problems on earth. They're not responsible of them, they're only responsible of the definition and deep meaning of the word "C++".
    Last edited by SuperKoko; November 14th, 2006 at 09:31 AM.
    "inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
    Club of lovers of the C++ typecasts cute syntax: Only recorded member.

    Out of memory happens! Handle it properly!
    Say no to g_new()!

  15. #15
    Join Date
    Nov 2002
    Location
    Foggy California
    Posts
    1,245

    Re: Exception Handling

    You've missed my point. I don't like the idea of undefined behavior. That allows the compiler vendors to allow demons flying out of my nose. I'm contacting Bjarne, Herb, and P.J. and team to change the standard -- every place that mentions undefined behavior, I want them to explicitly state that demons will fly out of the developer's nose .... Hmmm.... except I'm .... a developer and errr... don't always write bug free code.... ohhhh.... OK, let's just leave things as they are.
    Kevin Hall

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured