473,763 Members | 7,719 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

When to use exceptions

What I want to do is to read a 32-bit unsigned integer (let's call that
u32) in little-endian form from an fstream. Would it be better if my
function went like this:

// returns false if an error occurs reading the value
bool read(std::fstre am& stream, u32& value);

or this:

u32 read(std::fstre am& stream) throw(FileReadi ngException);

In general, what are some good guidelines for when something like the
first is preferred over something like the second, and vice-versa?

--
I am only a mirage.
Jul 23 '05 #1
13 1683
* kelvSYC:
What I want to do is to read a 32-bit unsigned integer (let's call that
u32) in little-endian form from an fstream. Would it be better if my
function went like this:

// returns false if an error occurs reading the value
bool read(std::fstre am& stream, u32& value);

or this:

u32 read(std::fstre am& stream) throw(FileReadi ngException);
Given only these two to choose from:

the first and only the first.

But also provide a throwing version like the second but without exception
specification.

In general, what are some good guidelines for when something like the
first is preferred over something like the second


Always. Exception specifications are very impractical and misleading in
C++. There are only a few forms that are acceptable, in certain contexts.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #2
> > // returns false if an error occurs reading the value
bool read(std::fstre am& stream, u32& value);

or this:

u32 read(std::fstre am& stream) throw(FileReadi ngException);


Given only these two to choose from:

the first and only the first.

But also provide a throwing version like the second but without exception
specification.


So a comprimise like so:

// throws exception if an error occurs reading the value, but is not
// specified in the prototype
u32 read(std::fstre am& stream);

would be acceptable C++ style then?

--
I am only a mirage.
Jul 23 '05 #3
* kelvSYC:
// returns false if an error occurs reading the value
bool read(std::fstre am& stream, u32& value);

or this:

u32 read(std::fstre am& stream) throw(FileReadi ngException);


Given only these two to choose from:

the first and only the first.

But also provide a throwing version like the second but without exception
specification.


So a comprimise like so:

// throws exception if an error occurs reading the value, but is not
// specified in the prototype
u32 read(std::fstre am& stream);

would be acceptable C++ style then?


1. What if you need i32 result, double result, and so forth?

2. What if you'd like to use this for a stream that's not an fstream?

3. The earlier quandary seems to indicate a non-throwing version can
come in handy, and there's no need to exclude it.

So perhaps

template< typename T >
void throwIf0( T nonzero, char const diagnostic[] )
{
if( !nonzero ){ throw std::runtime_er ror( diagnostic ); }
}

bool readBinary( std::istream& stream, u32& result ){ ... }

u32 u32FromBinary( std::istream& stream )
{
u32 result;
throwIf0( read( stream, result ), "my useful diagnostic" );
return result;
}

For text I'd just read text strings and convert them to whatever
they represent, because such functions are much cleaner and more
reusable, and because stream based text-to-other conversion is not
well-defined in C++ (the interface is there, the definition not).

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #4
> What I want to do is to read a 32-bit unsigned integer (let's call that
u32) in little-endian form from an fstream. Would it be better if my
function went like this:

// returns false if an error occurs reading the value
bool read(std::fstre am& stream, u32& value);

or this:

u32 read(std::fstre am& stream) throw(FileReadi ngException);


I prefer to throw when an error occurs. This ensures me that the execution
of the calling function stops. Without throwing I might forget handling the
error condition and such errors are hard to find during test.

Niels Dybdahl
Jul 23 '05 #5
On Mon, 6 Jun 2005 07:22:36 UTC, "Niels Dybdahl" <nd*@esko-graphics.com>
wrote:

<snip>
I prefer to throw when an error occurs. This ensures me that the execution
of the calling function stops. Without throwing I might forget handling the
error condition and such errors are hard to find during test.

Niels Dybdahl


My preference, as the designer and developer of a function, is to provide
adequate documentation about the behavior and abilities of said function.
As the user of functions that others have developed, I want to see such
documentation as well.

My reasoning is that at any location in a given fragment of code, an
error may occur. Some errors are more likely than others. Exception
based error reporting enforces the user to wrap all code levels with
appropriate exception handling code. This must be done often enough
that the user can actually find and correct the cause of an error
when it occurs. For any given level of functionality, there are many
possible errors to report -- whether they may be from exceptions or
other known sources.

Given a well documented interface, the user can then decide what
is an appropriate use for their needs. This includes handling
unexpected conditions.

Users need to handle errors at a reasonable level. Your preference
to use an exception to report "an expected file error" may be appropriate
for one developer and not another.

My preference for using exceptions is to use them very sparingly
and with good cause. Before exceptions were common, return codes
and other methods were commonplace. The user had to decide at what level
to check for these unexpected conditions. Exceptions give us a different
method of reporting errors. Now users are faced with handling both
methods all of the time. Your code could be quite complicated for
handling information (expected and unexpected behavior) for any non-trivial
function. When designing interfaces, please make it easy to understand
what the expected behavior is. I should be able to use nearly all
interfaces by reading just the interface documentation (.h and other files).
You should make it easy for the user to handle all errors and behaviors
appropriately. That has different meanings for different environments.
So, consider your user base when designing an interface.

Your suggestion that the interface provide both non-exception and
exception based functions is a good one. However, when that function
is non-trivial, you may find that writing both versions at a level that
can handle all errors appropriately may be a daunting task. The two
functions may not even look the same. Keeping them in-sync could be
difficult.

David
Jul 23 '05 #6
Niels Dybdahl wrote:
What I want to do is to read a 32-bit unsigned integer (let's call that
u32) in little-endian form from an fstream. Would it be better if my
function went like this:

// returns false if an error occurs reading the value
bool read(std::fstre am& stream, u32& value);

or this:

u32 read(std::fstre am& stream) throw(FileReadi ngException);


I prefer to throw when an error occurs. This ensures me that the execution
of the calling function stops. Without throwing I might forget handling
the error condition and such errors are hard to find during test.


However, if the calling code needs to know exactly where the reading failed,
it leads to excessive typing:

struct somestruct
{
long a;
long b;
long c;
};

//...

somestruct s;
try
{
s.a = read(stream);
}
catch (FileReadingExc eption& ex)
{
//... whatever
return; // or throw or whatever
}

try
{
s.b = read(stream);
}
catch (FileReadingExc eption& ex)
{
//... whatever
return; // or throw or whatever
}

try
{
s.c = read(stream);
}
catch (FileReadingExc eption& ex)
{
//... whatever
return; // or throw or whatever
}

//...

Jul 23 '05 #7
kelvSYC wrote:
// returns false if an error occurs reading the value
bool read(std::fstre am& stream, u32& value);

or this:

u32 read(std::fstre am& stream) throw(FileReadi ngException);

In general, what are some good guidelines for when something like the
first is preferred over something like the second, and vice-versa?


IMO that depends of the file format. If, for example, you are reading until
eof, the first way is best. If the format is fixed, and you know how much
data is in the file and a failure to read means that the file is corrupt or
unreadable, the second way allows cleaner code.

--
Salu2
Jul 23 '05 #8
Rolf Magnus wrote:
However, if the calling code needs to know exactly where the reading
failed, it leads to excessive typing:

struct somestruct
{
long a;
long b;
long c;
};

//...

somestruct s;
try
{
s.a = read(stream);
}
catch (FileReadingExc eption& ex)
{
//... whatever
return; // or throw or whatever
}

try
{
s.b = read(stream);
}
catch (FileReadingExc eption& ex)
{
//... whatever
return; // or throw or whatever
}


You can do something like that:

void readsome ( ..... , StatReadSome & stat)
{
.....
stat= ReadSomeNothing ;
s.a= read (stream);
stat= ReadSome_a;
s.b= read (stream);
stat= ReadSome_b;
....
}

--
Salu2
Jul 23 '05 #9
> > I prefer to throw when an error occurs. This ensures me that the
execution
of the calling function stops. Without throwing I might forget handling
the error condition and such errors are hard to find during test.
However, if the calling code needs to know exactly where the reading

failed, it leads to excessive typing:

struct somestruct
{
long a;
long b;
long c;
};

//...

somestruct s;
try
{
s.a = read(stream);
}
catch (FileReadingExc eption& ex)
{
//... whatever
return; // or throw or whatever
}

try
{
s.b = read(stream);
}
catch (FileReadingExc eption& ex)
{
//... whatever
return; // or throw or whatever
}

try
{
s.c = read(stream);
}
catch (FileReadingExc eption& ex)
{
//... whatever
return; // or throw or whatever
}

//...


No. You can just do:

s.a = read(stream);

s.b = read(stream);

s.c = read(stream);

No error checking code means that there is much less error checking code to
test. How often do you make systematic test of your error checking code ?

Niels Dybdahl
Jul 23 '05 #10

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

Similar topics

0
1546
by: John J. Lee | last post by:
Bare "except:", with no exception specified, is nasty because it can easily hide bugs. There is a case where it seemed useful to me in the past. Now it seems like a bad idea to me (but I think I might still be confused about it, hence this post). It's this: When you're processing a input from a file-like object connected to an external source like a network connection, disk file etc, you have to expect broken, and often malicious,...
10
1553
by: Jakob Bieling | last post by:
Hi, somehow the prejudice of exceptions being rather slow (compared to, ie. returning an error value and checking that) keeps sticking around .. at least around me. I guess this is also why I refrained from using them often. But are they 'slow' in general? I guess it also depends on how, when and where you use them. What I am looking for is a sort of guideline that explains where exceptions are approriate and where they are not. The...
8
2258
by: cat | last post by:
I had a long and heated discussion with other developers on my team on when it makes sense to throw an exception and when to use an alternate solution. The .NET documentation recommends that an exception should be thrown only in exceptional situations. It turned out that each of my colleagues had their own interpretation about what an "exceptional situation" may actually be. First of all, myself I’m against using exceptions extensively,...
5
1492
by: Joris Zwaenepoel | last post by:
Hi all, I don't think a solution exists, but maybe there is some option in Visual Studio that I do not know about. When developping (or debugging), I like to set the "exceptions" option to "break when the error is thrown", even for handled exceptions, because a general purpose error handler usually handles all unexpected exceptions. A side effect of that is that a break also happens when an exception occurs
4
1854
by: Steve | last post by:
I have read a couple articles online, read my Jesse Liberty book but I am still confused as to just what the best practices are for using exceptions. I keep changing how I'm working with them and it has now, after 15k lines of code resulted in a royal mess! It's my hope to ask some specific questions with scenario examples and that some of you might offer a little guidance or general suggestions. 1) string...
22
16944
by: dvestal | last post by:
Suppose I have this: class C { public delegate void MyEventHandler(); public event MyEventHandler MyEvent; public void foo() { MyEvent(); // NullReferenceException? } }
2
5294
by: pillappa | last post by:
Hi, I am hitting this error consistently and don't know why it's happening. I would like to define all exceptions for my project in one file and use them across the project. Here's a sample - exceptions.py - class MyException(StandardError): def __init__(self, error):
8
2441
by: Olivier BESSON | last post by:
Hello, VB.NET 1.1 IIS 6 I'm developping a winform client app of a web service of mine. I used to set the IDE with "halt in debugger" on "common language runtime exceptions". Every time i call a method of my service if have 2 first time exceptions
9
1931
by: =?Utf-8?B?UmFq?= | last post by:
How do I know which methods will throw exception when I am using FCL or other third party .Net library? I am developer of mostly native Windows applications and now .Net. After working few months in Java, I am thinking why Win32 APIs or even .Net documentation not clear on which methods will throw exception or what exceptions can be expected. Jave APIs clearly define exceptions that can be expected and enforces that we handle them. ...
0
9563
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
9386
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10144
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...
0
9997
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9937
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
9822
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...
0
6642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5270
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...
3
2793
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.