473,770 Members | 6,105 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
13 1684
Niels Dybdahl wrote:
> 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);


And how do I know whether s.c really contains a value read from the file?
No error checking code means that there is much less error checking code
to test.
And it leads to programs that print messages like "There was some error."
without letting the user know what the exact error actually was, because
that information got lost due to the missing error checking code.
How often do you make systematic test of your error checking code
?


You mean, you don't test how your program reacts to various errors in the
input data?

Jul 23 '05 #11
> > No. You can just do:

s.a = read(stream);

s.b = read(stream);

s.c = read(stream);
And how do I know whether s.c really contains a value read from the file?


It does. If an error occurred, the execution is breaked by an exception.
No error checking code means that there is much less error checking code
to test.


And it leads to programs that print messages like "There was some error."
without letting the user know what the exact error actually was, because
that information got lost due to the missing error checking code.
How often do you make systematic test of your error checking code
?


You mean, you don't test how your program reacts to various errors in the
input data?


No I do not mean that. I mean: do you go through your sourcecode to locate
all your error checking code and create test cases so that each error
checking code is tested for correct behaviour ? It is not nice to send out
an application where numerous code lines have never been executed.

Niels Dybdahl

Jul 23 '05 #12
Niels Dybdahl wrote:
> No. You can just do:
>
> s.a = read(stream);
>
> s.b = read(stream);
>
> s.c = read(stream);
And how do I know whether s.c really contains a value read from the file?


It does. If an error occurred, the execution is breaked by an exception.


Ok, bad example. What about s.b then? If an exception during reading s.c is
thrown, s.b contains a valid value, if an exception is thrown earlier, it
doesn't.
> No error checking code means that there is much less error checking
> code to test.


And it leads to programs that print messages like "There was some error."
without letting the user know what the exact error actually was, because
that information got lost due to the missing error checking code.
> How often do you make systematic test of your error checking code
> ?


You mean, you don't test how your program reacts to various errors in the
input data?


No I do not mean that. I mean: do you go through your sourcecode to locate
all your error checking code and create test cases so that each error
checking code is tested for correct behaviour ?


No.
It is not nice to send out an application where numerous code lines have
never been executed.


And you think it's better to leave that code out completely?

Jul 23 '05 #13
> >> > No. You can just do:
>
> s.a = read(stream);
>
> s.b = read(stream);
>
> s.c = read(stream);

And how do I know whether s.c really contains a value read from the
file?
It does. If an error occurred, the execution is breaked by an exception.
Ok, bad example. What about s.b then? If an exception during reading s.c

is thrown, s.b contains a valid value, if an exception is thrown earlier, it
doesn't.


So if an exception occurs, you have to treat all values gained in this
functionality as invalid. Code designed on returned error values have exact
the same problem. For local variables it is not a problem as they are
automatically destructed and removed. For global variables you will always
have the problem: What to do if the structure is only partly created due to
an error ?
No I do not mean that. I mean: do you go through your sourcecode to locate all your error checking code and create test cases so that each error
checking code is tested for correct behaviour ?


No.
It is not nice to send out an application where numerous code lines have
never been executed.


And you think it's better to leave that code out completely?


If the error still can be handled, as it can with exceptions, then yes. Deep
into the "read" function there are still error checking code that can throw
and I hope that the author of that function has tested that. At a high level
I would have a try/catch block that catches all errors and reports the
errors to the operator or to a log. I might have a few try/catch blocks for
cleaning up, but I try to avoid that as much as possible and use destructors
instead.
This has two advantages: Less untested code and my code consists of less
error handling, so that is easier to read and maintain.

Niels Dybdahl
Jul 23 '05 #14

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
1493
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
5295
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
9592
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
10231
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
10005
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
9871
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
8887
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7416
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
6679
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
5452
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2817
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.