473,549 Members | 2,627 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exception handling questions

Hi all,

I've got two somewhat general questions related to exception handling
in C++. My usual programming language is the lovely and flexible
Python, but for various reasons, including the need to interface with
third-party libraries, get extra performance, etc. I have to use C++.

Now in Python, being a dynamically typed language, everything is
pushed to the run-time. Additionaly, since the language does not
guarantee deterministic destruction of objects, there are try/finally
blocks everywhere and the release of resources is done *explicitly*.

In C++, the mindset is different. As far as I have managed to learn,
there are two grand rules to pay attention to:

- Use exceptions for run time conditions, assert's for
logical/programmer errors.

- Use RAII (resource acquisition is initialization) .

Is there any other big rule that I am missing?

As I have said earlier, one of the reasons I use C++ is when I have to
squeeze out more performance and optimizing the Python code is just
not enough. This leads me to my second question: what is the "penalty"
for using exceptions in C++? I just want to have an idea of the cost
in terms of space/time, an idea of "what to expect in general" when
using exceptions.

With my best regards,
G. Rodrigues
Jul 23 '05 #1
3 1903
"Gonçalo Rodrigues" <op*****@mail.t elepac.pt> wrote in message
news:8i******** *************** *********@4ax.c om...
Hi all,

I've got two somewhat general questions related to exception handling
in C++. My usual programming language is the lovely and flexible
Python, but for various reasons, including the need to interface with
third-party libraries, get extra performance, etc. I have to use C++.

Now in Python, being a dynamically typed language, everything is
pushed to the run-time. Additionaly, since the language does not
guarantee deterministic destruction of objects, there are try/finally
blocks everywhere and the release of resources is done *explicitly*.

In C++, the mindset is different. As far as I have managed to learn,
there are two grand rules to pay attention to:

- Use exceptions for run time conditions, assert's for
logical/programmer errors.

- Use RAII (resource acquisition is initialization) .

Is there any other big rule that I am missing?
I have no idea how to answer this question. The usual error for C++ newbies
is probably to use operator new way too much. I suppose this afflicts Java
programmers more than Python programmers. One thing to remember is that C++
classes are not automatically polymorphic as Python classes are. You have to
use the keyword "virtual" to get polymorphic behavior. There are too many
other differences to enumerate here.

I will suggest this though: use C++ standard library constructs such as
std::string and std::vector rather than the old C constructs of char* and
array. Effective usage of the standard library is what separates good from
bad C++ programmers IMHO. Plus it's easier.

As I have said earlier, one of the reasons I use C++ is when I have to
squeeze out more performance and optimizing the Python code is just
not enough. This leads me to my second question: what is the "penalty"
for using exceptions in C++? I just want to have an idea of the cost
in terms of space/time, an idea of "what to expect in general" when
using exceptions.
Exceptions are not expensive if you use them as they are meant to be used:
for exceptional situations. If you use them as control structures you can
run up a bill. I happened to be reading the Python cookbook last night and
saw a claim that using exceptions in Python to check things (in this case
whether a string contained a valid integer value) was highly pythonic. Such
uses are not typical in C++. However, using them for error handling is not
expensive and highly Bjarnic (a name I made up but which hasn't caught on
yet :).

One way or another, derive your exceptions from std::exception. I got into
an argument with someone on this point recently who insisted that it's a
mistake not to derive from std::runtime_er ror. Since one is derived from the
other I don't feel that strongly about it. std::runtime_er ror takes a string
argument which is convenient for error messages.

One other thing: C++ has a throw specification you can use in your
declarations such as:

void func() throw(); // promises not to throw any exceptions

I advise you not use them. If they did what they seem to promise they would
be useful, but they don't. For instance, the actual implementation of func()
may actually throw and everything compiles fine. :P

With my best regards,
G. Rodrigues


--
Cy
http://home.rochester.rr.com/cyhome/
Jul 23 '05 #2
GB
Cy Edmunds wrote:
One way or another, derive your exceptions from std::exception. I got into
an argument with someone on this point recently who insisted that it's a
mistake not to derive from std::runtime_er ror. Since one is derived from the
other I don't feel that strongly about it. std::runtime_er ror takes a string
argument which is convenient for error messages.


That would have been me.

I was not insisting it is a mistake. I was merely indicating the
intended use of the standard exception classes. The standard library
divides (most) exceptions at the top level into runtime errors and logic
errors. If you don't want to fit your exception into one of these two
categories, then by all means derive directly from std::exception.

Gregg
Jul 23 '05 #3
--- Gonçalo Rodrigues wrote:
In C++, the mindset is different. As far as I have managed to
learn, there are two grand rules to pay attention to:
And many others, I'm afraid. Any generally good programmer who
wants to start writing quality C++ code ought to get "Effective
C++" and "More Effective C++", by Scott Meyers. Get the CD
version, that has it all in HTML. There you'll find some 85
Rules to Live By. (Or, some say, 85 Reasons to Hate C++. You
can choose whichever spin you prefer.)

--- Cy Edmunds wrote: I happened to be reading the Python cookbook last night and
saw a claim that using exceptions in Python to check things (in
this case whether a string contained a valid integer value) was
highly pythonic.
Yep. And of course checking for end-of-container [in C++:
.... != container.end()] is usually done with exceptions in Python.
However, using them for error handling is not expensive and highly
Bjarnic (a name I made up but which hasn't caught on yet :).
No, it hasn't. I was going to prove you wrong, so I googled and
found exactly one other usage of the term. On dBforums. By you.
We'll see what we can do to get this term into mainstream usage.

BTW, I'm feeling rather Bjarnic today.
C++ has a throw specification you can use in your
declarations such as:

void func() throw(); // promises not to throw any exceptions

I advise you not use them. If they did what they seem to promise
they would be useful, but they don't.


I agree with your advice, but I would be careful with them even if
they worked as promised (is that an un-Bjarnic thought?). Do you
really want a "please crash" statement in release code? I don't.
Here is a safe way to use an exception spec:

void func()
#ifndef NDEBUG
throw()
#endif
; // The legendary "Lone Semicolon", defender of good syntax

Jul 23 '05 #4

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

Similar topics

2
2585
by: tom | last post by:
Hi, I am developing a WinForm application and I am looking for a guide on where to place Exception Handling. My application is designed into three tiers UI, Business Objects, and Data Access Layer. My questions is where should I put exception handling: 1) Should it be put in all significant methods in all layers? 2) Should I create an...
44
4164
by: craig | last post by:
I am wondering if there are some best practices for determining a strategy for using try/catch blocks within an application. My current thoughts are: 1. The code the initiates any high-level user tasks should always be included in a try/catch block that actually handles any exceptions that occur (log the exception, display a message box,...
3
1433
by: Gary | last post by:
I'm in the application_error event. I want to know which aspx experienced the exception. Is there any easy way? Thanks, G
4
1829
by: sm | last post by:
Hi, I have a couple of questions with regards to handling errors and exceptions. 1. If I use On Error goto Errhandler ... Errhandler:
1
1029
by: Robin Tucker | last post by:
I keep reading about exception handling being preferable to "return codes". I would like to implement some kind of consistent use of exceptions in my code, but am finding it hard to come up with some definitive rules. For example, I Try...Catch....Finally, whenever I am either dealing with an interop object or something that needs to be...
11
5555
by: chopsnsauce | last post by:
Here's the example: Dim frm As New FORM1 Try frm.show Catch ex As Exception msgbox ex.message
3
4259
by: Adil Akram | last post by:
I'm new to C#. Please answer my following questions about c# exception handling. What happens and how an exception handled if it occurs in "catch" block while already processing another exception. In an exception "catch" block I am showing a dialog box to user with option of "try again" or "cancel". How can I implement the "try again"...
6
3365
by: Mohan | last post by:
Hi, I am learning the Exception Handling in C++. I wrote a small program using Exception Handling. I am using Vistual Studio 6. It is working fine in Win32 Debug build, but it is not catching the exception in Win32Release mode.
1
2906
by: Efi Merdler | last post by:
Hi, I created a user control, but instead of handling exception in the user control level I prefer to handle them in the containing form. In the load event of the containing form I'm using: entryWindow.Error += new EventHandler(Page_Error); when entryWindow is my user control. Two questions:
0
7521
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...
0
7720
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. ...
1
7473
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...
0
6044
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...
1
5369
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...
0
3501
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...
0
3483
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1944
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
1
1061
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.