473,395 Members | 1,386 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Error handling?

I have a class that contains:
class MyArray {
public:
MyArray(int a) : num(a){}

void generate() {
ip = new int[a];
}

int& operator[](int Index) {
return ip[Index];
}
....
....

private:
int* ip;
int num;

};
But I assume its rather error-prone. What kind of techniques exist for
handling memory allocation and indexing errors? Eg. is it necessary to
catch a possible bad_alloc thrown by new or out_of_range etc. I would
like to know what the standard approaches towards error-safe code are in
the above example.
May 17 '07 #1
3 1412
desktop wrote:
I have a class that contains:
class MyArray {
public:
MyArray(int a) : num(a){}

void generate() {
ip = new int[a];
}

int& operator[](int Index) {
return ip[Index];
}
...
...

private:
int* ip;
int num;

};
But I assume its rather error-prone. What kind of techniques exist for
handling memory allocation and indexing errors? Eg. is it necessary to
catch a possible bad_alloc thrown by new or out_of_range etc. I would
like to know what the standard approaches towards error-safe code are in
the above example.
The main one? Use std::vector instead.
May 17 '07 #2
edd
On 17 May, 20:29, desktop <f...@sss.comwrote:
I have a class that contains:

class MyArray {
public:
MyArray(int a) : num(a){}

void generate() {
ip = new int[a];
}

int& operator[](int Index) {
return ip[Index];
}
...
...

private:
int* ip;
int num;

};

But I assume its rather error-prone. What kind of techniques exist for
handling memory allocation and indexing errors? Eg. is it necessary to
catch a possible bad_alloc thrown by new or out_of_range etc. I would
like to know what the standard approaches towards error-safe code are in
the above example.
Preferably use std::vector<>, either out the box, or as the basis for
your implementation. You'll never have to worry about memory leaks.
Copy construction and assignment will "just work". You can forward
your operator[] calls to the vector's at() member function if you want
bounds checking or it's operator[] if you don't.

If you really insist on using new[], then at the very least:

- move the initialisation of the pointer in to the initialiser list in
the constructor.
- consider using a more appropriate type to represent sizes and
indices (my knee-jerk reaction would be to opt for size_t)
- make sure you delete[] the pointer in the destructor
- define what it means for a MyArray to be copy constructed and copy-
assigned, or disallow them completely using the private-and-undefined-
copy-machinery trick.

If the number of elements in a MyArray can change you have a lot of
extra stuff to consider, too, in terms of crafting an efficient
implementation and exception safety. In particular look at the
strategies vector<implementations use to expand their capacity when
elements are appended/inserted and how they interplay with exceptions.

Of course this all begs the question, why don't you just use an
std::vector<intas-is? The people that designed it have taken care of
the tricky implementation details for you.

Kind regards,

Edd

May 17 '07 #3

desktop <ff*@sss.comwrote in message...
I have a class that contains:

class MyArray {
public:
MyArray(int a) : num(a){}
void generate() {
// ip = new int[a];

ip = new int[ num ];
}

int& operator[](int Index) {
return ip[Index];
}
...
...
private:
int* ip;
int num;
};

But I assume its rather error-prone. What kind of techniques exist for
handling memory allocation and indexing errors?
std::vector<intMyArray( 1, 42);

try{
int aaa = MyArray.at(2);
}
catch(std::out_of_range const &oor){
std::cout<<" caught = "<<oor.what()<<std::endl;
}

<G>
Eg. is it necessary to
catch a possible bad_alloc thrown by new or out_of_range etc. I would
like to know what the standard approaches towards error-safe code are in
the above example.
"necessary" depends on how much damage will be done if the memory allocation
fails inside your class. <G>

In "Thinking in C++" vol.2, Eckel/Allison have a whole chapter dedicated to
'exception handling', and show how to do it inside a class. It should give
you a good start on that. ( it may not be perfect due to changes in standard
since it was 'final'-ized. ).

Get "Thinking in C++", 2nd ed. Volume 1&2 by Bruce Eckel
(available for free here. You can buy it in hardcopy too.):
http://www.mindview.net/Books/TICPP/...ngInCPP2e.html

See: // : C01:InitExcept.cpp From "Thinking in C++, Vol2"
[ preview snippet, modified for ostream output ]
class Derived : public Base {
std::ostream &dout;
public:
class DerivedExcept{
char const *msg;
public:
DerivedExcept( char const *msg) : msg(msg){}
char const* what() const { return msg; }
};
Derived(int j, std::ostream &out)
try : Base(j, out), dout(out){ // Ctor body
// 'Base' just throws BaseExcept();
out<<"This won't print"<<std::endl;
}
catch( BaseExcept& ){
out<<"catch(BaseExcept&) ";
throw DerivedExcept("Base subobject threw");;
}
~Derived(){ // Dtor
dout<<"~Derived() Dtor called."<<std::endl;
}
}; // class Derived

{ using std::cout; // main or function
try{
Derived d( 3, cout );
}
catch( Derived::DerivedExcept &ddd ) {
cout<<"catch( DerivedExcept &)\n";
cout<<ddd.what()<<std::endl; // "Base subobject threw"
}
}

Or, check the book you have for something similar.
--
Bob R
POVrookie
May 17 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: WSeeger | last post by:
When creating a new class, is it encouraged to always include error handling routines within your LET and GET procedures? It's seems that most text books never seem to include much about error...
12
by: Christian Christmann | last post by:
Hi, assert and error handling can be used for similar purposes. When should one use assert instead of try/catch and in which cases the error handling is preferable? I've read somewhere that...
6
by: Squirrel | last post by:
I have a command button on a subform to delete a record. The only statement in the subroutine is: DoCmd.RunCommand acCmdDeleteRecord The subform's recordsource is "select * from tblVisit order...
13
by: Thelma Lubkin | last post by:
I use code extensively; I probably overuse it. But I've been using error trapping very sparingly, and now I've been trapped by that. A form that works for me on the system I'm using, apparently...
21
by: Anthony England | last post by:
Everyone knows that global variables get re-set in an mdb when an un-handled error is encountered, but it seems that this also happens when the variable is defined as private at form-level. So...
3
by: Stefan Johansson | last post by:
Hi all I'am moving from Visual Foxpro and have a question regarding "best practice" error handling in vb .net. In VFP I have always used a "central" error handling object in order to have a...
4
by: Al Williams | last post by:
Hi, I have error handling in place throughout my application. I also start the application wrapped in error handling code to catch any unexpected exceptions (i.e. exceptions that occur where I...
10
by: Anthony England | last post by:
(sorry for the likely repost, but it is still not showing on my news server and after that much typing, I don't want to lose it) I am considering general error handling routines and have...
0
by: Lysander | last post by:
Thought I would give something back with a few articles. This article is a bit of code to add error handling. When I have time, I want to write articles on multilingual databases, and Access...
9
by: MrDeej | last post by:
Hello guys! We have an SQL server which sometimes makes timeouts and connection errors. And we have an function witch writes and updates data in 2 tables on this server. When the SQL server error...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.