c++ - Catch error when QList index is out of bounds -
i developing application blackberry 10 , when try element 2 qstringlist while list contains 1 element, application crashs.
i using following code catch type of error:
try { //a code accesses qstringlist index out of bounds } catch (exception e) { }
but exception not caught , application crashes.
i tried catch (std:exception& e) , catch(...) , didn't work too.
how can use try catch catch error?
accessing qlist
out of range doesn't throw exception. instead, assumes checked index in range (what happens if isn't true explained below).
actually, not bad design design of container class: (in of cases) know indices in range. if qt should react out-of-bound accesses throwing exceptions, means want rely on check, means check has done (even if don't need qt check it). qt instead assume provide valid index. in debug builds, gets checked assertion , if assertion isn't met program terminates with reason (you can track nicely debugging), in release mode check isn't done @ all, silently produces undefined behavior if index out of bounds still accessing raw memory in data structure. fast possible, requires index valid.
assertions terminate process if aren't met, meaning can't "catch" kind of error. avoid in first place, i.e. test index being in range before accessing list.
note (maybe all?) container classes provide access "real" index check (no crash, in release build), i.e. defined , intended behavior when out of bounds. qlist
, function is:
t value(int index, t fallbackvalue)
it tries access element @ index
bounds check. if index not in range (or in associative containers: not found), fallbackvalue
have given returned. second parameter defaults default-constructed t
. note value has constructed if index correct. why in cases want check might better check manually branch, , construct default value if needed (in particular if need evaluate expensive expression construct fallback value):
if (index < mylist.count()) // check upper bound in scenario foo = mylist[index]; else foo = expensivefunctionreturningmyfallbackvalue();
Comments
Post a Comment