473,657 Members | 2,801 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exception Handling constructor

Hi,

Here is a piece of code where the constructor throws an exception.

class A
{
int n;
public:
A()
try{
{
throw 10;
}
}
catch(const int &e)
{
cerr<<""<<endl;
}
A(const int &i)
try{
{
if(i == 0)
throw 10;
n = i;
}
}
catch(const int &e)
{
cerr<<"Exceptio n raised in parameterised constructor"<<e ndl;
}
int get_value()
{
return n;
}
};

void main()
{
A obj(10);
cout<<obj.get_v alue()<<endl;
A obj1(0);
}
When execute the above code I got the following output on g++
compiler.

10
Exception raised in parameterised constructor
terminate called after throwing an instance of 'i'

What is the logical state of an object if the constructor throws an
exception, here the object obj1.
And in case if the constructor has a parameter initialization list,
how should the try{} catch(){}
be.
Thanks in advance.

Regards
Sunil
Jan 13 '08 #1
4 2909
On 2008-01-13 10:32, Sunil Varma wrote:
Hi,

Here is a piece of code where the constructor throws an exception.

class A
{
int n;
public:
A()
try{
{
throw 10;
}
}
catch(const int &e)
{
cerr<<""<<endl;
}
A(const int &i)
try{
{
if(i == 0)
throw 10;
n = i;
}
}
catch(const int &e)
{
cerr<<"Exceptio n raised in parameterised constructor"<<e ndl;
}
int get_value()
{
return n;
}
};

void main()
{
A obj(10);
cout<<obj.get_v alue()<<endl;
A obj1(0);
}
When execute the above code I got the following output on g++
compiler.

10
Exception raised in parameterised constructor
terminate called after throwing an instance of 'i'

What is the logical state of an object if the constructor throws an
exception, here the object obj1.
When the end of a function try block handler in a constructor is reached
the exception is rethrown (which is why terminate() is called), so the
effects should be the same as throwing an exception in a normal
constructor, i.e. there is no object obj1.
And in case if the constructor has a parameter initialization list,
how should the try{} catch(){} be.
struct Foo
{
int nr;
Foo(int n)
try
: nr(n)
{
// So some more construction
}
catch(std::exce ption& e)
{
// Handle exception
}
};

Notice that the initialisation list comes between the 'try' and the '{'.
If an exception is thrown either in the initialisation list of the body
of the try-block control will be transferred to the appropriate catch-
block.

--
Erik Wikström
Jan 13 '08 #2
Thanks a lot.
It works fine.
If a constructor of a class is in a try block, then it's better
creating an object dynamically than creating it statically, for that
class.

Sunil

On Jan 13, 4:37 pm, Erik Wikström <Erik-wikst...@telia. comwrote:
On 2008-01-13 10:32, Sunil Varma wrote:
Hi,
Here is a piece of code where the constructor throws an exception.
class A
{
int n;
public:
A()
try{
{
throw 10;
}
}
catch(const int &e)
{
cerr<<""<<endl;
}
A(const int &i)
try{
{
if(i == 0)
throw 10;
n = i;
}
}
catch(const int &e)
{
cerr<<"Exceptio n raised in parameterised constructor"<<e ndl;
}
int get_value()
{
return n;
}
};
void main()
{
A obj(10);
cout<<obj.get_v alue()<<endl;
A obj1(0);
}
When execute the above code I got the following output on g++
compiler.
10
Exception raised in parameterised constructor
terminate called after throwing an instance of 'i'
What is the logical state of an object if the constructor throws an
exception, here the object obj1.

When the end of a function try block handler in a constructor is reached
the exception is rethrown (which is why terminate() is called), so the
effects should be the same as throwing an exception in a normal
constructor, i.e. there is no object obj1.
And in case if the constructor has a parameter initialization list,
how should the try{} catch(){} be.

struct Foo
{
int nr;
Foo(int n)
try
: nr(n)
{
// So some more construction
}
catch(std::exce ption& e)
{
// Handle exception
}

};

Notice that the initialisation list comes between the 'try' and the '{'.
If an exception is thrown either in the initialisation list of the body
of the try-block control will be transferred to the appropriate catch-
block.

--
Erik Wikström
Jan 13 '08 #3
Sunil Varma <su*******@gmai l.comwrote:
If a constructor of a class is in a try block, then it's better
creating an object dynamically than creating it statically, for that
class.
Not necessarily, the two concepts aren't related. For example, several
of the vector constructors can throw, yet no one recommends creating
them dynamically rather than statically...
Jan 13 '08 #4
On Jan 13, 1:22 pm, Sunil Varma <sunil....@gmai l.comwrote:
If a constructor of a class is in a try block, then it's
better creating an object dynamically than creating it
statically, for that class.
Just the opposite, I'd say. If you allocate using new, and
something throws later, you have to delete in the throw block.
Except that in many cases, there will be no pointer to the
object in the throw block. In general:

-- don't allocate dynamically unless you have to;

-- if the lifetime of the object is local (e.g. you have to
allocate dynamically because the object is polymorphic,
although it has the same lifetime as a normal local object),
use a smart pointer (boost::scoped_ ptr or std::auto_ptr);
and

-- if the lifetime of the object is really dynamic, keep it in
a smart pointer until it has been "exported"---there is a
pointer to the object where ever the pointer to the object
is expected to be. (std::auto_ptr is very good for this.)

--
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
Jan 14 '08 #5

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

Similar topics

9
2601
by: Kevin Goodsell | last post by:
If I'm writing a class that will be used as an exception, what kinds of things do I need to watch out for? For example, is it necessary to make sure that the members of the class don't throw? Suppose my class has one or more std::string members. These could throw bad_alloc on construction or copy. Is this dangerous? Here's an example: #include <string> class SimpleException
3
2745
by: Master of C++ | last post by:
Hi, I am an absolute newbie to Exception Handling, and I am trying to retrofit exception handling to a LOT of C++ code that I've written earlier. I am just looking for a bare-bones, low-tech exception handling mechanism which will allow me to pass character information about an error and its location from lower-level classes. Can you please critique the following exception handling mechanism in terms of my requirements ?
3
2788
by: Tony Johansson | last post by:
Hello! I'm reading in a book about C++ and there is something that I want to ask you about. It says "since the constructor does not return any value, the only way to handle errors that occur during its execution is to use exception handling. You can deal with errors that occur during the execution of the constructor's body by using try block
9
4993
by: David B | last post by:
Why is it so difficult to report bugs to Microsoft? I have a documented bug and an small test example. I don't really see why I should have to pay to tell them about it... Anyway, the following code exhibits the bug. If it is built and run from Visual Studio.NET 2003 in debug mode it works correctly as expected. However, if built in Release mode it fails with an "uncaught exception" error, although the exception does have a valid...
44
4206
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, etc.). 2. Low-level operations that are used to carry out the high level tasks
1
2222
by: thejackofall | last post by:
Howdy? Good. I am getting this error when the Exception Handling Application Block when it tries to create my exception handler. Here is the error. Constructor on type 'MyCompany.Exception.MyCompanyExceptionHandler' not found. In my code, the contructor for the handler is as follows: public MyCompanyException() : base()
3
3399
by: matko | last post by:
This is a long one, so I'll summarize: 1. What are your opinions on raising an exception within the constructor of a (custom) exception? 2. How do -you- validate arguments in your own exception constructors? I've noticed that, f.ex., ArgumentException accepts null arguments without raising ArgumentNullException. Obviously, if nothing is to be supplied to the exception constructor, the default constructor should
6
218
by: asm23 | last post by:
Hi, everyone, I'm learning <<thinking c++>volume Two, and testing the code below. ///////////////////////////////////////////////////////////////////////////// //: C01:Wrapped.cpp #include <iostream> #include <cstddef> using namespace std;
4
1777
by: DHS1 | last post by:
Hey guys. I have a lab that is due in two weeks, but I wanted to start on it now. Problem is, I'm at home during christmas break so I can't ask my professors. Here's my problem: I am given a very fragile program and I have to add the exception handling and error checking and pretty much make it uncrashable. I will show just one small step in this lab. If you can answer it, I think I'll be able to do the rest. I just need to get headed in...
0
8820
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
8718
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
8499
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
7314
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
6162
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
4150
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
2726
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
1937
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1601
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.