exception try, catch

This is a discussion on exception try, catch within the C++ Programming forums, part of the General Programming Boards category; I was making a 2d "safe" array class and was using exceptions if an array out of bounds index was ...

  1. #1
    ... arjunajay's Avatar
    Join Date
    May 2005
    Posts
    203

    Question exception try, catch

    I was making a 2d "safe" array class and was using exceptions if an array out of bounds index was passed. the code fragment would be like so:
    Code:
    //in array header.
    double& Matrix::operator()(unsigned long int r, unsigned long int c){
        if(array)
            if( (r<n_r)&&(c<n_c) )
                return array[(r*n_c) + c];
            else
                throw"\n\n\t##Array Index Out Of Bounds.\n\n";
        else
            throw"\n\n\t##Memory NOT Allocated yet.\n\n";
    }
    //in main().
    int main(){
        Matrix m(5, 5);
    
        try{
            m(5, 5);
        }catch(const char* e){
            std::cout<<"\n# Exception Caught :"<<e;
        }
    
        return 0;
    }
    My question is that when I didn't type in the 'const' shown in bold, my catch block did'nt catch any exceptions. Why should 'catch' bother whether the string literal thrown was constant or not? It took me a really long time and lot of experimenting untill I got that 'const' in there.

    What should I do so that my 'catch' catches all 'char*'s whether 'const' or not?
    P.S. This code is for eucational purposes only. so please don't advice me to use vectors or any thing instead of re-inventng the wheel.

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Code:
    #include <stdexcept>
    
    try
    {
      throw std::runtime_error("Help, it won't work!");
    }
    catch(std::exception& Exception)
    {
      std::cout << Exception.what();
    }
    If you really want to use char*'s perhaps two cathes after each other, one char* the other const char*?
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    847
    A function with a const char * argument can handle char * as well. A char * argument means that the function may attempt to change the string while a const char * means it will not. Functions with a char * argument shouldn't accept a const char * pointer because attempting to alter a constant will result in a segmentation fault.
    Last edited by Quantum1024; 02-19-2006 at 10:49 AM.

  4. #4
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    And the same goes for catch-blocks. A catch block:
    Code:
    try { ... } catch(sometype e) {}
    Catches any exception of a type that is convertible to sometype.
    When you throw a string literal, the thrown type is const char*, which is not convertible to char*; thus, the catch won't catch it.

    That said, you shouldn't throw string literals anyway. Best practice is to always throw a class that somehow derives from std::exception.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  5. #5
    ... arjunajay's Avatar
    Join Date
    May 2005
    Posts
    203

    Thumbs up Thanks...

    Code:

    Code:
    #include <stdexcept>
    
    try
    {
      throw std::runtime_error("Help, it won't work!");
    }
    catch(std::exception& Exception)
    {
      std::cout << Exception.what();
    }
    That said, you shouldn't throw string literals anyway. Best practice is to always throw a class that somehow derives from std::exception.
    Thanks...

  6. #6
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    Just to add to what was said: when the compiler sees any string literal(which is something between double quotes like "Array Index Out Of Bounds"), the compiler slaps a '\0' onto the end of it and stores it in memory, and then returns it's address. So, you are throwing the address in memory of that string literal. Additionally, the string literal stored in memory is const(that's just the way it is), so you cannot change it. For instance you can't do this:
    Code:
    char* str = "Hello World.";
    str[0] = 'a';
    It will compile, but it will crash.

    So, you are throwing a pointer to a const char array. That means if you list the parameter of your catch statement as a char*, it cannot catch a const char*. A function or catch statement can modify the value that is being pointed to if it is stored in a char* parameter variable. However, an argument that is of type const char* says that the value pointed to shall not be changed under any circumstances. So, the argument will hurry by your catch statement in fear--lest it gets changed by just looking in the catch statement's general direction.

    As was pointed out above, a parameter variable that is declared as a const char* can catch a char* as well. If the argument is pointing to a non-const char, the argument doesn't care whether its modified: change it, don't change it, it's all good. So if a function says it will not modify the value by declaring the function parameter const, the non-const argument could care less, and it will gladly stop and visit that waypoint along its journey.
    Last edited by 7stud; 02-19-2006 at 08:47 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Exception handling in a large project
    By EVOEx in forum C++ Programming
    Replies: 7
    Last Post: 01-25-2009, 06:33 AM
  2. exception handling
    By coletek in forum C++ Programming
    Replies: 2
    Last Post: 01-12-2009, 04:28 PM
  3. How do I catch an exception thrown from a linked DLL?
    By 6tr6tr in forum C++ Programming
    Replies: 2
    Last Post: 04-24-2008, 07:49 AM
  4. unexpected exception handler
    By George2 in forum C++ Programming
    Replies: 2
    Last Post: 01-10-2008, 04:49 AM
  5. how do I catch exception in c?
    By beon in forum C Programming
    Replies: 10
    Last Post: 11-21-2006, 06:45 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21