473,804 Members | 3,447 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Handling errors within templated classes

I have a Stack class that works fine. In particular, when it
encounters an error, it cout's a msg and exits. However, I'd like to
change it to report the error and continue with dummy data as
necessary. My problem is how to construct dummy data consistent with
the type the class was instantiated with.

My class, stripped to it's essentials for my purpose here, is:

template <class T>
class Stack {
public:
T pop()
{
if ( top < 0 )
{
cout << "Error\n";
return WHAT;
}
return st[top--];
}
private:
int top;
T st[5];
};

How might the "return WHAT;" statement be coded to yield something
like:

if ( typeof(T) == int
doThis(0);
else
doThat("xxx");

It was recommended by one person that I check out "template
specialization" , which I Googled. I found several offerings, but I
don't think they were applicable to the situation I'm trying to
address (but maybe I'm wrong).

I'm running MinGW on WinXP-Pro/.SP2.

Thanks in Advance,
Richard

Oct 30 '07 #1
8 1509
RichardOnRails wrote:
I have a Stack class that works fine. In particular, when it
encounters an error, it cout's a msg and exits. However, I'd like to
change it to report the error and continue with dummy data as
necessary. My problem is how to construct dummy data consistent with
the type the class was instantiated with.

My class, stripped to it's essentials for my purpose here, is:

template <class T>
class Stack {
public:
T pop()
{
if ( top < 0 )
{
cout << "Error\n";
return WHAT;
You can obtain a default value for T by using the default constructor
(provided T has one):

return ( T() );
}
return st[top--];
}
private:
int top;
T st[5];
};

How might the "return WHAT;" statement be coded to yield something
like:

if ( typeof(T) == int
doThis(0);
else
doThat("xxx");

It was recommended by one person that I check out "template
specialization" , which I Googled. I found several offerings, but I
don't think they were applicable to the situation I'm trying to
address (but maybe I'm wrong).
I am not following the doThis() vs. doThat() example. In particular, I have
no idea what the "xxx" is doing there.
BTW: The stack class looks fishy. Poping off an empty stack should trigger
an assert(). If you really want the program to continue, you may opt for
throwing an exception. If you return invented data, client code has no
chance detecting that there way an error.

Also: a hard-coded limit size of 5 is (a) rather small and (b) not
necessary at all. Why don't you use std::stack<>?
Best

Kai-Uwe Bux
Oct 30 '07 #2
On Oct 30, 1:20 am, Kai-Uwe Bux <jkherci...@gmx .netwrote:
RichardOnRails wrote:
I have a Stack class that works fine. In particular, when it
encounters an error, it cout's a msg and exits. However, I'd like to
change it to report the error and continue with dummy data as
necessary. My problem is how to construct dummy data consistent with
the type the class was instantiated with.
My class, stripped to it's essentials for my purpose here, is:
template <class T>
class Stack {
public:
T pop()
{
if ( top < 0 )
{
cout << "Error\n";
return WHAT;

You can obtain a default value for T by using the default constructor
(provided T has one):

return ( T() );
}
return st[top--];
}
private:
int top;
T st[5];
};
How might the "return WHAT;" statement be coded to yield something
like:
if ( typeof(T) == int
doThis(0);
else
doThat("xxx");
It was recommended by one person that I check out "template
specialization" , which I Googled. I found several offerings, but I
don't think they were applicable to the situation I'm trying to
address (but maybe I'm wrong).

I am not following the doThis() vs. doThat() example. In particular, I have
no idea what the "xxx" is doing there.

BTW: The stack class looks fishy. Poping off an empty stack should trigger
an assert(). If you really want the program to continue, you may opt for
throwing an exception. If you return invented data, client code has no
chance detecting that there way an error.

Also: a hard-coded limit size of 5 is (a) rather small and (b) not
necessary at all. Why don't you use std::stack<>?

Best

Kai-Uwe Bux
Hi Kai-Uwe,

Thanks for your response.

Your questions/suggestions are well founded. However, I was using a
"toy" application to test alternative error-handling strategies. One
was to trap the error, display a msg and exit the app. However,
sometimes it's desirable to recover somehow from errors so that
additional errors can be exposed in a single pass through all the
calls in an app.

I finally came up with a way to do that. If you're still interested,
tell me what you think of the following example, which compiles with
the current version of MinGW's g++ and executes as intended: it
exposes two errors.

Regards,
Richard
// TemplateErrHand ler.c++
// K:\_Projects\C+ +\MinGW\04a_Tem plateErrHandler \

#include <string>
#include <iostream>
using namespace std;

template <class T>
class MyClass {
public:
MyClass() {}
T MyFn()
{
/* Invalid attampts:
return -1029384756; // Error flag
return "My Message"; // Error flag
*/

// Correct attempt:
cout << "ERROR: An error was detected; execution continuing\n";
T tObj;
return tOverloaded(tOb j);
}
private:
int n;
int tOverloaded(int val) {return -1029384756;}
char* tOverloaded(str ing val){return "My Message";}
};

int main ()
{
MyClass<intintI nstance;
cout << "From intInstance: " << intInstance.MyF n() << "\n";

MyClass<strings trInstance;
cout << "From strInstance: " << strInstance.MyF n() << "\n";
}



Oct 30 '07 #3
Hi

RichardOnRails wrote:
I was using a "toy" application to test alternative error-handling
strategies. One was to trap the error, display a msg and exit the app.
However, sometimes it's desirable to recover somehow from errors so that
additional errors can be exposed in a single pass through all the
calls in an app.
Could you explain what kind of errors you want to detect?
I finally came up with a way to do that. If you're still interested,
tell me what you think of the following example, which compiles with
the current version of MinGW's g++ and executes as intended: it
exposes two errors.
Please explain in more detail what exactly you want to do, because I cannot
extract it from the example you give (nor from your previous posting...)
#include <string>
#include <iostream>
using namespace std;

template <class T>
class MyClass {
public:
MyClass() {}
T MyFn()
{
/* Invalid attampts:
return -1029384756; // Error flag
return "My Message"; // Error flag
*/

// Correct attempt:
cout << "ERROR: An error was detected; execution continuing\n";
T tObj;
return tOverloaded(tOb j);
Okay... you create a default object tObj of type T. The value you return is
the return value of another overloaded function, named tOverloaded. This
return value does not at all depend on tObj (Question: Why do you create
the object, then?) Furthermore, for types T where no conversion to either
int or std::string exists, the instantiation of MyClass<T>::MyF n will fail.
}
private:
int n;
You _never_ use n. Why do you declare it?
int tOverloaded(int val) {return -1029384756;}
char* tOverloaded(str ing val){return "My Message";}
Don't use the string-literal-to-char-pointer conversion. It's only there for
C-compatibility (string literals are immutable). I think you wanted to
return string there. Furthermore: Is there _any_ reason why you return "My
Message" and -1029384756?
};

int main ()
{
MyClass<intintI nstance;
cout << "From intInstance: " << intInstance.MyF n() << "\n";

MyClass<strings trInstance;
cout << "From strInstance: " << strInstance.MyF n() << "\n";
}
So you are using MyClass<Tto return some arbitrary T value.

WHY?

And why don't you simply use:

template<typena me TT some_value();
template<string some_value<stri ng>() { return "My Message"; }
template<int some_value<int> () { return -1029384756; }

int main()
{
cout << "From int: " << some_value<int> () << "\n";
cout << "From str: " << some_value<stri ng>() << "\n";
}

And what does this have to do with error handling and/or exposing two
errors?

Markus

Oct 30 '07 #4
On Oct 30, 9:42 am, Markus Moll <markus.m...@es at.kuleuven.ac. be>
wrote:
Hi

RichardOnRails wrote:
I was using a "toy" application to test alternative error-handling
strategies. One was to trap the error, display a msg and exit the app.
However, sometimes it's desirable to recover somehow from errors so that
additional errors can be exposed in a single pass through all the
calls in an app.

Could you explain what kind of errors you want to detect?
I finally came up with a way to do that. If you're still interested,
tell me what you think of the following example, which compiles with
the current version of MinGW's g++ and executes as intended: it
exposes two errors.

Please explain in more detail what exactly you want to do, because I cannot
extract it from the example you give (nor from your previous posting...)
#include <string>
#include <iostream>
using namespace std;
template <class T>
class MyClass {
public:
MyClass() {}
T MyFn()
{
/* Invalid attampts:
return -1029384756; // Error flag
return "My Message"; // Error flag
*/
// Correct attempt:
cout << "ERROR: An error was detected; execution continuing\n";
T tObj;
return tOverloaded(tOb j);

Okay... you create a default object tObj of type T. The value you return is
the return value of another overloaded function, named tOverloaded. This
return value does not at all depend on tObj (Question: Why do you create
the object, then?) Furthermore, for types T where no conversion to either
int or std::string exists, the instantiation of MyClass<T>::MyF n will fail.
}
private:
int n;

You _never_ use n. Why do you declare it?
int tOverloaded(int val) {return -1029384756;}
char* tOverloaded(str ing val){return "My Message";}

Don't use the string-literal-to-char-pointer conversion. It's only there for
C-compatibility (string literals are immutable). I think you wanted to
return string there. Furthermore: Is there _any_ reason why you return "My
Message" and -1029384756?
};
int main ()
{
MyClass<intintI nstance;
cout << "From intInstance: " << intInstance.MyF n() << "\n";
MyClass<strings trInstance;
cout << "From strInstance: " << strInstance.MyF n() << "\n";
}

So you are using MyClass<Tto return some arbitrary T value.

WHY?

And why don't you simply use:

template<typena me TT some_value();
template<string some_value<stri ng>() { return "My Message"; }
template<int some_value<int> () { return -1029384756; }

int main()
{
cout << "From int: " << some_value<int> () << "\n";
cout << "From str: " << some_value<stri ng>() << "\n";

}

And what does this have to do with error handling and/or exposing two
errors?

Markus
Hi,

Did you read the original post? I think that explains what I was
trying to do.

In Ruby, if I suspected that an object reference I had referred either
to a string or a number, I could write:

if obj.responds_to (zero?) puts "obj refers to a number"
else if obj.responds_to (upcase) puts "obj refers to a string"
else puts "Who knows what obj refers to?"

Stoustrup omitted such a capability from C++. I wanted effect such a
capability, and that's what my example does.

Maybe the following version will be more illustative.
--
Richard
// TemplateErrHand ler.c++
// K:\_Projects\C+ +\MinGW\04a_Tem plateErrHandler \

/*TEST RESULTS:
K:\_Projects\C+ +\MinGW\04a_Tem plateErrHandler >g++ TemplateErrHand ler.c
++

K:\_Projects\C+ +\MinGW\04a_Tem plateErrHandler >a
ERROR: An error was detected; execution continuing
From intInstance: -1029384756
ERROR: An error was detected; execution continuing
From strInstance: My Message

K:\_Projects\C+ +\MinGW\04a_Tem plateErrHandler >
*/

#include <string>
#include <iostream>
using namespace std;

template <class T>
class MyClass {
public:
MyClass() {}
T MyFn()
{
/* Invalid attampts:
return -1029384756; // Error flag
return "My Message"; // Error flag
*/

// Correct attempt:
cout << "ERROR: An error was detected; \n"
<< " execution will continue \n"
<< " by returning an artifical value.\n";
T tObj;
return tOverloaded(tOb j);
}
private:
int n;
int tOverloaded(int val) {return -1029384756;}
char* tOverloaded(str ing val){return "My Message";}
};

int main ()
{
MyClass<intintI nstance;
cout << "Return value from intInstance: " << intInstance.MyF n() << "\n
\n";

MyClass<strings trInstance;
cout << "Return value from strInstance: " << strInstance.MyF n() << "\n
\n";
}
Oct 30 '07 #5
private:
int n;
You're right: I never used it. I originally thought I needed it, and
then forgot to remove it. I've done so now.
---
R.

Oct 30 '07 #6
RichardOnRails wrote:
On Oct 30, 1:20 am, Kai-Uwe Bux <jkherci...@gmx .netwrote:
RichardOnRails wrote:
Your questions/suggestions are well founded. However, I was
using a "toy" application to test alternative error-handling
strategies. One was to trap the error, display a msg and
exit the app. However, sometimes it's desirable to recover
somehow from errors so that additional errors can be exposed
in a single pass through all the calls in an app.
There are two standard solutions for this problem, depending on
the types of errors you're interested in. If the error is
something "exceptiona l", i.e. something which won't normally
occur (like disk full or insufficient memory), you should
definitely raise an exception. If the error is something
"normal" (just about any errors in user input, for example), the
usual solution is to use some variant of the Barton and Nackman
"Fallible" idiom, perhaps extended to allow additional
information concerning the error. (There's an implementation
supporting extended error codes at my site:
http://kanze.james.neuf.fr/code-en.html, in the Basic
subsystem.)

Another, less frequently used idiom is to provide a callback.
I finally came up with a way to do that. If you're still
interested, tell me what you think of the following example,
which compiles with the current version of MinGW's g++ and
executes as intended: it exposes two errors.
It has two major flaws: the calling code doesn't know that there
was an error, and it outputs error messages to std::cout, which
is not necessarily where the client code wants them.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Oct 31 '07 #7
"Alf P. Steinbach" <al***@start.no wrote in news:13******** *****@corp.supe rnews.com:
>subsystem.)

That's good advice, but the advice about choosing exceptions or not
based on how "exceptiona l" the situation is IMO ungood advice -- no
matter that it is advice that's (mindlessly, and with reference to some
"authority" ) repeated by a majority of C++ programmers.

In addition to being so vague and subjective as to be worthless, it's
worthless because what can be "exceptiona l" in one context need not be
exceptional in some other context.

Instead, use exceptions where they provide clarity and are most
practical -- same advice as for use of loop constructs and other
language constructs.


I like the rule of thumb given on the boost site. Use exceptions if what you want is
stack unwinding, otherwise use an error code. In other words, if you generally expect
the immediate caller to handle the error in some way, don't use exceptions. If you
expect the error to be handled at a higher level than the immediate caller, then an
exception might well be the way to go.

joe
Oct 31 '07 #8
On Oct 31, 11:37 am, Joe Greer <jgr...@doublet ake.comwrote:
"Alf P. Steinbach" <al...@start.no wrote innews:13****** *******@corp.su pernews.com:
subsystem.)
That's good advice, but the advice about choosing exceptions or not
based on how "exceptiona l" the situation is IMO ungood advice -- no
matter that it is advice that's (mindlessly, and with reference to some
"authority" ) repeated by a majority of C++ programmers.
In addition to being so vague and subjective as to be worthless, it's
worthless because what can be "exceptiona l" in one context need not be
exceptional in some other context.
Instead, use exceptions where they provide clarity and are most
practical -- same advice as for use of loop constructs and other
language constructs.

I like the rule of thumb given on the boost site. Use exceptions if what you want is
stack unwinding, otherwise use an error code. In other words, if you generally expect
the immediate caller to handle the error in some way, don't use exceptions. If you
expect the error to be handled at a higher level than the immediate caller, then an
exception might well be the way to go.

joe
Hey guys, thanks for your additional ideas. I was just playing around
with a stack implementation I downloaded because I hadn't written any C
++ since I retired 6 years ago. Because it was using it merely as a
toy I added rudimentary error handling with messages directed to
stdout with immediate exit thereafter.

Then I thought I should play with the idea of adding a boolean DEBUG
symbol to allow reporting multiple error in a single session.
However, allowing continued execution after issuing an error message
proved problematical when the offending method's definition specified
a templated return type.

In the latter case, I had to be conjure a suitable dummy return
value. And that value had to be a literal of of the templated type.
I had in mind the ease with which I could that in Ruby, which is rich
in metaprogramming facilities. But nothing came to mind for C++.
Hence the post.

Then the idea of creating overload methods came to me and I was a
happy campler. So I'm signing off from this thread with thanks to all
respondents. I will keep your ideas in mind if I ever do serious C++
programming again.
--
Richard

Nov 1 '07 #9

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

Similar topics

2
3275
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 handling within classes. Just hoping to hear some programmer's thoughts on error handling.
7
6009
by: Noor | last post by:
please tell the technique of centralize exception handling without try catch blocks in c#.
11
3279
by: Master of C++ | last post by:
Hi, I am writing a simulation package in C++, and so far I've written about 8000 lines of code and have about 30 classes. I haven't used C++ exceptions so far (for various reasons). The only two "resources" I use are memory and file I/O and whenever there is a memory allocation failure or file I/O failure I just simply call a custom assert-type function to check, print a error message and abort. This seems to be OK for now (for the...
1
1976
by: Noor | last post by:
Hi all, I am trying to catch all types of exceptions from a app regardless of whether it is in debugger mode( VS development environment) or run the.exe file outside the IDE. My App contains the thousand of classes and I do not want to use the Try Catch block in each class. Because it is logically similar to GOTO statement. I want to prevent exception from being swallowed.
4
2527
by: aaj | last post by:
Hi all I have an automated application, that runs in the middle of the night. If certain 'non system' errors occur (things like malformed files, missing files etc..), I send an automatic Email and write a record to the database. This is handled in a class. When these errors occur, once Emailed and written I want to just end the App, simple as that.
5
4297
by: Michael | last post by:
Hello, I have a separate Database class that handles any database work that all my asp.net pages can use. My problem is, many times I use try/catch to catch errors, and I want to output these errors to the webpage with response.write(). Unfortunately Response.anything from within my class generate a "Response is not declared" error. How can I get Response to work from within a class, or is there a better way to handle errors in...
4
7622
by: James Radke | last post by:
Hello, I am looking for guidance on best practices to incorporate effective and complete error handling in an application written in VB.NET. If I have the following function in a class module (note that this class module represents the business layer of code NOT the gui layer): Public Function Test(ByVal Parm1 As Integer, ByVal Parm2 As Integer) As SqlDataReader ' Declare the SQL data layer class Dim oSQL As New...
35
3811
by: jeffc226 | last post by:
I'm interested in an idiom for handling errors in functions without using traditional nested ifs, because I think that can be very awkward and difficult to maintain, when the number of error checks gets about 3 or so. It also gets very awkward in nested loops, where you want to check for normal loop processing in the loop condition, not errors. Yes, you could put some generic exit flag in the loop condition, but when you're simply done if...
2
2939
by: domehead100 | last post by:
I have a templated class, CDerived: template <typename TValue, typename TDraw, typename TEdit ...> class CDerived : public CBase { TValue m_Value public: TValue& GetValue() const {
0
9711
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10594
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10331
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10087
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7631
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5529
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4306
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.