473,808 Members | 2,832 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do I write exception safty code?

I want to write some small programs with exception safety, but I don't how
to write. Because my programs wrap C-api function( example: win32 api). I
don't find my direction. I wish any hot heart man to help me. My english is
too bad. I am sorry! Thanks!

#include "windows.h"
#include <string>
//
#ifndef FILE1_H
#define FILE1_H
namespace wukexin{
//
std::string Fileattrib_to_s tr( const DWORD attrib );
//
std::string Filetime_to_str ( const FILETIME* x );
//
class Cfile_informati on
{
public:
explicit Cfile_informati on(std::string fname){initiali zer(fname);};
//~Cfile_informat ion(){destroyer ();};
void print();
protected:
//friend ostream& operator<< (std::ostream& os, const Cfile_informati on&
file);
private:
void initializer(std ::string fname);
void destroyer();
bool destroySuccess_ ;
HANDLE hfile_;
std::string fname_;
WIN32_FIND_DATA file_;
};
}
#endif //file1.h
////////////////
file.cpp
//**
void Cfile_informati on::initializer (std::string fname){
WIN32_FIND_DATA file;
//std::cout<<fnam e<<"construct success!\n";
hfile_=FindFirs tFile(fname.c_s tr(),&file_);
if(INVALID_HAND LE_VALUE == hfile_){
//std::cout<<"Fin dFirstFile(fnam e,&file) run error!\n"<<std: :endl;
throw <<"FindFirstFil e(fname,&file) run error!\n";
}
destroySuccess_ =false;
}
//
Cfile_informati on::~Cfile_info rmation(){
if( !destroySuccess _ ){
try{
destroyer();
}
catch(){
// codes
}
};
//**
Sep 12 '07 #1
8 1700
On Sep 12, 3:34 pm, "dragon9" <maigre_dra...@ 126.comwrote:
I want to write some small programs with exception safety, but I don't how
to write. Because my programs wrap C-api function( example: win32 api). I
don't find my direction. I wish any hot heart man to help me. My english is
too bad. I am sorry! Thanks!

#include "windows.h"
#include <string>
//
#ifndef FILE1_H
#define FILE1_H
namespace wukexin{
//
std::string Fileattrib_to_s tr( const DWORD attrib );
//
std::string Filetime_to_str ( const FILETIME* x );
//
class Cfile_informati on
{
public:
explicit Cfile_informati on(std::string fname){initiali zer(fname);};
//~Cfile_informat ion(){destroyer ();};
void print();
protected:
//friend ostream& operator<< (std::ostream& os, const Cfile_informati on&
file);
private:
void initializer(std ::string fname);
void destroyer();
bool destroySuccess_ ;
HANDLE hfile_;
std::string fname_;
WIN32_FIND_DATA file_;
};}

#endif //file1.h
////////////////
file.cpp
//**
void Cfile_informati on::initializer (std::string fname){
WIN32_FIND_DATA file;
//std::cout<<fnam e<<"construct success!\n";
hfile_=FindFirs tFile(fname.c_s tr(),&file_);
if(INVALID_HAND LE_VALUE == hfile_){
//std::cout<<"Fin dFirstFile(fnam e,&file) run error!\n"<<std: :endl;
throw <<"FindFirstFil e(fname,&file) run error!\n";
}
destroySuccess_ =false;
}
//
Cfile_informati on::~Cfile_info rmation(){
if( !destroySuccess _ ){
try{
destroyer();
}
catch(){
// codes
}
};
//**
Firstly, it's not a good practice to send non-pointer non-reference
types by const, because a copy it will be used anyway.
Another idea is to return an error code from the function and pass
through references your data, for example:
std::string Fileattrib_to_s tr( const DWORD attrib );
bool Fileattrib_to_s tr( DWORD attrib, std::string& retVal );

Exceptions should be used in exceptional cases only, everything else
should be treated as errors.
Exception mechanism is very slow as well.

I think you should refactor your code.

Use it carefully!

Sep 12 '07 #2
On Sep 12, 8:34 am, "dragon9" <maigre_dra...@ 126.comwrote:
I want to write some small programs with exception safety, but I don't how
to write. Because my programs wrap C-api function( example: win32 api). I
don't find my direction. I wish any hot heart man to help me. My english is
too bad. I am sorry! Thanks!

#include "windows.h"
#include <string>
//
#ifndef FILE1_H
#define FILE1_H
namespace wukexin{
//
std::string Fileattrib_to_s tr( const DWORD attrib );
//
std::string Filetime_to_str ( const FILETIME* x );
//
class Cfile_informati on
{
public:
explicit Cfile_informati on(std::string fname){initiali zer(fname);};
//~Cfile_informat ion(){destroyer ();};
void print();
protected:
//friend ostream& operator<< (std::ostream& os, const Cfile_informati on&
file);
private:
void initializer(std ::string fname);
void destroyer();
bool destroySuccess_ ;
HANDLE hfile_;
std::string fname_;
WIN32_FIND_DATA file_;
};}

#endif //file1.h
////////////////
file.cpp
//**
void Cfile_informati on::initializer (std::string fname){
WIN32_FIND_DATA file;
//std::cout<<fnam e<<"construct success!\n";
hfile_=FindFirs tFile(fname.c_s tr(),&file_);
if(INVALID_HAND LE_VALUE == hfile_){
//std::cout<<"Fin dFirstFile(fnam e,&file) run error!\n"<<std: :endl;
throw <<"FindFirstFil e(fname,&file) run error!\n";
}
destroySuccess_ =false;
}
//
Cfile_informati on::~Cfile_info rmation(){
if( !destroySuccess _ ){
try{
destroyer();
}
catch(){
// codes
}
};
//**
Read Sutter's Exceptional C++. In it, there's a series of examples
that
systematically walks the reader through the implementation of a stack
container and teaches the fundamentals of exception safety along the
way.

A must read for any serious C++ programmer IMHO.
Sep 12 '07 #3
Thanks very much, my question is how to wrap C-api functions with exception
safety.
example:
FindFirstFile() ,etc.
Sep 12 '07 #4

dragon9 <ma***********@ 126.comwrote in message...
Thanks very much, my question is how to wrap C-api functions with
exception
safety.
example:
FindFirstFile() ,etc.
FindFirstFile() is windows, so, your best bet on that is to try a windows
NG. This group is for C++ (standard) language.
#include <iostream>
#include <exception>
#include <stdexcept>

class MyError : public std::runtime_er ror { public:
MyError( std::string const &msg = "") : std::runtime_er ror(msg){}
};

void SomeFunc(){
// you find an error that you can not recover from here, so you do:
throw MyError( "Rats, I really hate when that happens!!");
return; // it won't get here
}

int main() try {

// - your code here -

SomeFunc(); // for test

std::cout<< "main() finished"<<std: :endl;
return 0;
} // main()

catch( MyError const &Me ){
std::cout<< "main() caught MyError: "
<<Me.what()<<st d::endl;
return 1;
}
catch( std::exception const &Se) {
std::cout<< "main() caught exception: "
<<Se.what()<<st d::endl;
return 1;
}
catch( ... ) {
std::cout<<"cau ght unknown"<<std:: endl;
return 1;
}
See "Thinking in C++" vol.2
"Part 1: Building Stable Systems, 1: Exception Handling.

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
FAQ http://www.parashift.com/c++-faq-lite

--
Bob R
POVrookie
Sep 13 '07 #5
On Sep 13, 1:29 am, "dragon9" <maigre_dra...@ 126.comwrote:
Thanks very much, my question is how to wrap C-api functions with exception
safety.
example:
FindFirstFile() ,etc.
If it's a function from a C API, you don't need to do anything
with regards to exception safety, since the function will never
throw. Otherwise, it couldn't be used from C. In particular,
both the Windows API and Posix are C, and none of the functions
in these API's ever raise an exception. (I think. I'm 100%
sure about Posix, but I think Windows is the same.)

If you want the function to throw for certain types of errors,
you'll have to wrap it, check the return status, and manually
throw the exception you want for the types of errors you want.
Regardless of whether you want to throw or not, I would strongly
recommend wrapping all of the system API in some sort of
platform neutral C++ interface; I use something roughly similar
to java.io.File, for example, with different implementations for
Windows and for Posix/Linux. And some of the functions in this
class do throw, for certain types of errors.

--
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

Sep 13 '07 #6
Thank everyone. Now I haven't any good done, but I simple use
std::runtime_er ror to wrap it.

--
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
Sep 14 '07 #7
On 2007-09-14 15:10, dragon9 wrote:
Thank everyone. Now I haven't any good done, but I simple use
std::runtime_er ror to wrap it.

--
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
Please, do not use other peoples signatures, it really confuses people.

--
Erik Wikström
Sep 14 '07 #8
Sorry, I knows.
Sep 15 '07 #9

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

Similar topics

1
6828
by: bdinmstig | last post by:
I refined my attempt a little further, and the following code does seem to work, however it has 2 major problems: 1. Very limited support for XPath features Basic paths are supported for elements, attributes, ".", and "..", plus also the "" predicate format is supported - however, only one predicate per path step is supported, and expr must be a relative path. 2. Poor performance
5
4298
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...
1
7511
by: Phil Sandler | last post by:
Hello all, Thanks in advance for any help with this. I am trying to get sample code to run from Michael Russell's excellent article on removing whitespace: http://www.codeproject.com/aspnet/WhitespaceFilter.asp I have also tried his updated version, which can be found (in a zip file) here:
3
1099
by: dinny | last post by:
If I have the problem that I can't access form controls because it's not the main thread, can I instead store the values in global variables, and then in the main thread have a timer that updates the controls from the global variables?
7
5189
by: david.topham | last post by:
Hi The code below demostrates an issue I'm having with with NetworkStream: using System; using System.Net.Sockets; namespace TCPCTest { class Class1
2
21978
by: Ilkka | last post by:
I have created an C++ application with Windows Forms, ADO and SQL server 2005. Now I need to change something and started debugging the code. Then suddenly I receive an error. "An unhandled exception of type 'System.AccessViolationException' occurred in mscorlib.dll Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt." The progran ends on a windows form designer...
0
789
by: Buddy Home | last post by:
Hello, I'm trying to upload a file programatically and occasionally I get the following error message. Unable to write data to the transport connection: An established connection was aborted by the software in your host machine. Stack Trace at System.Net.Sockets.NetworkStream.Write(Byte buffer, Int32 offset, Int32
3
14063
by: Buddy Home | last post by:
Hello, I'm trying to upload a file programatically and occasionally I get the following error message. Unable to write data to the transport connection: An established connection was aborted by the software in your host machine. Stack Trace at System.Net.Sockets.NetworkStream.Write(Byte buffer, Int32 offset, Int32
6
4245
by: Anders J | last post by:
Hi We have some code that runs in a EventReceiver ItemAdded handler. The code must be thread-safe since it is iterating a List to find the max number of a column and assigns it + 1 to the Item that was added. If it was not thread-safe, two items could get the same number (which must be unique). So how do we garantee this in the event handler? Is locking on "this" enough? I guess not since other types of Event Handlers could as well...
0
9600
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
10374
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...
0
10114
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
9196
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
7651
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
6880
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
5548
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
4331
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
3
3011
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.