Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: [C++] exception handling problem  (Read 2861 times)

0 Members and 1 Guest are viewing this topic.

chrz

  • Newbie
  • *
  • Posts: 8
    • View Profile
[C++] exception handling problem
« on: December 30, 2008, 04:20:32 pm »
I get a bad exit code on closure, but the catch-block didnt get executed on me or do i have to code myself the throwing of an exception?

im using gcc version 4.3.2 on mingw/msys

Code: [Select]
#include <iostream>
#include <stdexcept>
#include <vector>

using std::vector;
using std::cout;
using std::cerr;
using std::endl;
using std::out_of_range;

int main()
{
    vector<int> intVec;
    try {
        int integer = intVec[-1];
        cout << "This won't get executed :)" << endl;
    }
    catch(out_of_range &e)
    {
        cout << "This won't get executed too :( on my machine" << endl;
        cerr << e.what() << endl;
    }
    catch(...)
    {
        cerr << "unhandled exception" << endl;
    }
}

dewyatt

  • Jr. Member
  • **
  • Posts: 75
    • View Profile
    • http://dewyatt.blogspot.com
[C++] exception handling problem
« Reply #1 on: December 31, 2008, 03:41:01 am »
This is obviously not SFML-specific.
The General forum is for general SFML-related stuff.

You would have been better off posting on a C++ forum.
Anyways, operator[] does not do range checking.
Use the at() member function:
http://www.cplusplus.com/reference/stl/vector/at.html

This would work:
Code: [Select]

#include <iostream>
#include <stdexcept>
#include <vector>

using std::vector;
using std::cout;
using std::cerr;
using std::endl;
using std::out_of_range;

int main()
{
    vector<int> intVec;
    try {
        int integer = intVec.at(-1);
        cout << "This won't get executed :)" << endl;
    }
    catch(out_of_range &e)
    {
        cout << "This won't get executed too :( on my machine" << endl;
        cerr << e.what() << endl;
    }
    catch(...)
    {
        cerr << "unhandled exception" << endl;
    }
}

chrz

  • Newbie
  • *
  • Posts: 8
    • View Profile
[C++] exception handling problem
« Reply #2 on: December 31, 2008, 02:40:28 pm »
sorry i saw other posts who were not sfml specific, so i asked my question here. Thank you very much for the answer!

dewyatt

  • Jr. Member
  • **
  • Posts: 75
    • View Profile
    • http://dewyatt.blogspot.com
[C++] exception handling problem
« Reply #3 on: December 31, 2008, 03:09:39 pm »
No problem. :)

 

anything