C++ :: Catching Exceptions From Initializer List

Jan 4, 2015

In order to test catching exceptions from an initializer list, I deliberately did bad practice by hard coding an argument to a ctor that would cause a std::bad_allocto be thrown. Obviously better practice is to send a variable, but that would cause a compile error, so I hard coded a value.

The program I wrote creates Prime Numbers up to a specified limit which is an argument to the ctor of type std::size_t. The program works fine IMO, using g++ in cygwin:

$ time ./PrimesExe
Limit is 2000000
148933 Primes Created

real 0m1.210s
user 0m1.123s
sys 0m0.046s

Now when I send something invalid like a negative number or something too big for std::size_t, the program seems to run indefinitely, when compiled with g++ under cygwin. I haven't tested it yet on Linux.

However, if I do the same on VS2013 express, it takes about 15 seconds to print the expected caught exception message. I was not expecting it to take so ridiculously long compared to the reasonable amount of work involved in doing primes up to 2 million.

I have read up about what is involved in catching exceptions: stack unwinding, keeping track of what needs to be destroyed etc. But this is 1 object with 1 ctor argument, no Base classes or any other complications. So why such a long or indefinite amount of time?

This whole example is probably contrived, and I am wondering whether exceptions is the right tool for this - it is similar to the divide by zero problem, or could be considered a programming error to call a ctor with a bad argument?

Also, catching an exception thrown by an initalizer list seems a bit awkward in that one seems to have enclose the creation of the object and all subsequent uses of it (and any code in between ) in the same try block, otherwise it goes out scope. I suppose I could try to write a wrapper function that returns a smart pointer reference to a valid object, but I would have to test the validity of it's return too. That's the awkward part - there is probably a better way?

Are there any recommended ways of recovering from initializer list exception, that is, to allow the user to enter a new hopefully valid value and try to create the object again?

View 2 Replies


ADVERTISEMENT

C++ :: Algorithmic Initializer List?

Jan 22, 2014

Is there some way to generate an initializer list algoritmically?

In the case I'm thinking of, I want to initialize a map<> to pair<key, constant> over all expected values of key.

Obviously i could write a loop to initialize after construction, but it would be nice if it could be done in one statement.

View 1 Replies View Related

C++ :: Using Initializer List As Function Parameter

Nov 26, 2014

#include <iostream>
#include <initializer_list>
using namespace std;
void doSomething(std::initializer_list<int> list) {
} int main() {
doSomething({2,3,6,8});
return 0;
}

I write a small piece of code like above. But I can not compile it successfully. I try it both with and without the line "using namespace std", but nothing worked.

The error list: Symbol 'initializer_list' could not be resolved

I use Eclipse CDT and GCC 4.9.1.

View 3 Replies View Related

Visual C++ :: Initializer List - No Such File Or Directory

Oct 21, 2013

I have a project that compiles fine with VS 2010. As I compile it with VS 2012 it generates the entitled error. Why?

View 5 Replies View Related

C++ :: Colon Usage (single And Double) Member Initializer List?

Aug 27, 2013

The below code is taken from the open source 7zip project (7z920CPP7zipUIFileManagerBrowseDialog.h)

Code:
class CBrowseDialog: public NWindows::NControl::CModalDialog {

What does the single colon (CBrowseDialog:) mean? Is that Initializer List?

I know the double colon (NWindows::NControl::CModalDialog) is Scope Resolution Operator.

Why is (: public NWindows::NControl::CModalDialog) used with the class declaration?

Similar code is found through out the project along with class declarations.

View 2 Replies View Related

Visual C++ :: Catching A Dialog Box?

Dec 9, 2013

What I want is simple: I want to catch a dialog box!

The dialog box pops very frequently in a website. We have to put a username and password and press OK. I checked with spy++. It doesn't have any child windows. So catching the dialog box with windows API is ruled out. It must be a HTML dialog. I have to get DOM COM interfaces of the dialog.

Another option may be to make an add-on to get the interface to IWebBrowser2 and get the events fired. The title of the dialog box is "Authentication Required". If the events will be fired for that dialog box, I can check the title using IHTMLDocument2::get_Title.But will the events be fired for HTML dialog box? How to catch that desturbing dialog box.

View 2 Replies View Related

C/C++ :: Catching Base Class Exception As Reference

Jul 23, 2013

class BaseExcep {
protected:
      std::string message;  
public:
      BaseExcep(std::string);
      virtual void printException();

[Code] .....

Here i need to find which exception type is actually thrown.

Whether it is DerivedExcep1 or DerivedExcep2 or  BaseExcep itself.

I can't use dynamic_cast in this, since it is a reference ....

View 5 Replies View Related

C++ :: Developing Application Without Exceptions

Feb 27, 2015

Is it possible to develop any application without exceptions? I don't want to try and catch exceptions and remove it.but I want to write codes which should never create exceptions is it possible?

View 3 Replies View Related

C++ :: Exceptions Thrown During Initialization?

Jul 8, 2014

How exactly would one go about throwing an exception from an object's constructor?

Take a look at this snippet:

#include <iostream>
#include <exception>
class ExceptionFoo : public std::exception {
virtual const char* what() const throw() {

[Code].....

View 8 Replies View Related

C++ :: Custom Exceptions With Default Behaviour

May 24, 2013

I've been pondering which of these 2 approaches would make for the best interface for a library: Defining custom exceptions with specific names for different error scenarios but with standard behaviour, or simply using the predefined exceptions from the STL.

This is my current approach:
Code:
namespace rpp
{
class ConnectionError : public std::exception
{
public:
ConnectionError(const std::string &p_err);

[Code] .....

This seems to make for more descriptive code but it adds no functionality and the implementations are completely identical, which seems "off" to me, somehow.

View 8 Replies View Related

C++ :: Assignment Operator But With Some Member Exceptions

Jan 9, 2015

The task is to use the assignment operator of a class, but change all the data except certain ones. For example, below we are to assign all Person data of 'other' except for 'name' and 'ID':

#include <iostream>
#include <string>
struct Person {
std::string name;
int ID, age, height, weight;

[Code] .....

Name = Bob
ID = 2047
Age = 38
Height = 183
Weight = 170

Name = Frank
ID = 5025
Age = 25
Height = 190
Weight = 205

Bob pretends to be Frank, but keeps his name and ID.

Name = Bob
ID = 2047
Age = 25
Height = 190
Weight = 205

But I think the way I did it is pretty lousy (note the wasted steps changing the name and ID only to revert them back? So the ideal solution should require no wasted steps, unlike the method above, and changes to what the exclusions should be should be in only one place (not two like above). Of course, we assume that Person shall have many, many data members (and constantly increasing), so that simply defining Person::operator= (const Person& other) to handle all data except for 'name' and 'ID' is out of the question.

View 3 Replies View Related

C++ :: How To Handle The Exceptions Not Caught By Try / Catch

Nov 2, 2014

Here is an example,

Code:

int main()
{
try{
int y = 0;
int x = 2/y;
}
catch(...)
{
cout<<"catch it"<<endl;
}
return 0;
}

If you try, you will find out that catch(...) couldn't catch exception divided by zero. How'd we catch such exceptions?

View 4 Replies View Related

Visual C++ :: Getting Exceptions On Windows 7 And 8 On Different Parts Of Code?

Feb 25, 2015

I'm Getting exceptions on Windows 7 and Windows 8 on different parts of the Code? Why this can be happening, why the difference in behavior?

View 6 Replies View Related

C/C++ :: Expected Initializer Before Int

Jan 21, 2015

#include <iostream>
int ival1
int ival2=1
int summe
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {

[Code] .....

If I compile it I've got these errors

[Error] expected initializer before 'int'

recipe for target 'rechnen.o' failed

View 14 Replies View Related

C/C++ :: Error / Expected Initializer Before String

Nov 15, 2014

I'm working on a school project learning C++. I'm running into an error I can't seem to find the answer for (see topic title).

main.cpp
#include <iostream>
#include <string>
#include "Signature.h"
#include "Genome.h"
using namespace std;
// Calling Function
int main() {
Signature Sig1; // Create Signature object
Genome gString1; // Create Genome object

[code]....

View 1 Replies View Related

C++ :: Output BPM Excess Elements In Scalar Initializer

Dec 11, 2014

Im trying to output an array to a bmp file but i keep getting and error that says excess elements in scalar initializer.

i have tried both of these codes and still get the same error.

float pond[n][n];
int outputBMP("finaldata.bmp", (float*)pond, 499, 499);
float pond[n][n];
val=&pond[n][n];
int outputBMP("finaldata.bmp", (float*)val, 499, 499);

View 1 Replies View Related

C++ :: Processing Structured Arrays - Too Many Initializer Values

Apr 22, 2013

I working on an assignment that processes an array of structs. In the main function I am attempting to declare an array of Author structures with 3 elements. It is supposed to be initialized to set all of the string fields (the names and book titles) to "NONE", and the double fields (the prices) to zero. This is supposed to be done in one statement, not using loops. Here is what I have.

struct BookInfo struct Author
{ {
string title; string authorName;
double price; BookInfo books[SIZE] //SIZE = 3
}; };

//prototype for function to print the content of array on screen
void showInfo(Author a[], int size);

[Code] .....

I was under the impression that an array can only hold the values of one data type. So doubles and strings in the same array doesn't make sense to me. However, that's the example my teacher drew up. The error keeps telling me that there are too many initializer values.

View 4 Replies View Related

C++ :: Extended Initializer Lists Flag On Class Constructor

Apr 8, 2013

I just got this warning from codeblocks:

Code: extended initializer lists only available with -std=c++11 or -std=gnu++11 that I belive is due to having initialized a class array in the constructor somewhat like this:
Code: class xpto {
public;
xpto():num{25,25}{}
int num[2];
};

Since the code I'm developing is not meant to be compiled only by me and I want to ensure there are no incompatibilities with other machines I would like to kow whats the best way to initialize the array that is not c++11 dependent.

Is there no way to do it directly on the constructor "pre-instructions" (don't know the correct designation for the initialization section)? or do I have to put the instructions on the constructor body.

View 2 Replies View Related

C++ :: Template Class For Matrix Manipulation - Expected Initializer Before Constant

Jan 29, 2013

I wrote a template class for Matrix manipulation. The compiler cannot compile the source and complains

Matrix.h:144:41: error: expected initializer before ‘const’

What is the problem of the code enclosed below?

#ifndef MATRIX_H
#define MATRIX_H
/**
* @file Matrix.h
*The Matrix template class written for simplify the matrix manipulation.
*/

#include <cassert>
using namespace std;
template<typename T>
class Matrix {
int rows,cols;

[Code] .....

View 6 Replies View Related

C# :: Field Initializer Cannot Reference The Non-static Field / Public Var

Apr 12, 2015

So I have this class

class DataBase
{
// Change the connection path here to your own version of the database
public SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)v11.0;AttachDbFilename=|DataDirectory|UberDatabase.mdf;Integrated Security=True;");
public DataBase()
{
}
}

And in the same namespace as this class I have a form that calls it like so:

DataBase dBase = new DataBase();
SqlCommand trythis = new SqlCommand("Register", dBase.con);

However, I'm getting the field initializer error on dBase.con. I'm not sure why, but when I call the database from another file (program.cs) it works fine this way.

View 8 Replies View Related

C++ :: Why Does HP / Microsoft STL List Use Same Structure For List Head And Node

Apr 23, 2013

From HP / Microsoft (Visual Studio C++) <list>:

Code:
struct _Node
{ // list node
_Genptr _Next; // successor node, or first element if head
_Genptr _Prev; // predecessor node, or last element if head
_Ty _Myval; // the stored value, unused if head
};

The stored value is wasted space for the list head. Is there any advantage to implementing list using the same structure for a list head and node?

View 6 Replies View Related

C :: Linked List / Adding Element To Beginning Of List

Dec 31, 2014

Code:

// Write a function called insertEntry() to insert a new entry into a linked list.

Have the procedure take as arguments a pointer to the list entry to be inserted (of type struct entry as defined in this chapter), and a pointer to an element in the list after which the new entry is to be inserted.

// The function dveloped in exercise 2 only inserts an element after an existing element in the list, thereby prenting you from inserting a new entry at the front of the list.

(Hint: Think about setting up a special structure to point to the beginning of the list.)

#include <stdio.h
struct entry1 {
int value;
struct entry1 *next;
};

[code]...

This is a working version of the exercise, but I don't think I'm doing what's asked. I was able to add an element to the beginning of the list using an if statement, not creating a special structure that points to the beginning of the list. How would I go about creating a special structure that points to the beginning of the list to add a new element at the beginning of the list?

View 8 Replies View Related

C# :: Display List Of MSMQ Messages In A List Box

Jan 20, 2015

I'm trying to display a list of MSMQ messages in a list box based on a drop-down list holding the environment.So i've setup the binding and i know that the list loads but nothing shows up in the list? I should be setting like a display member or something but i'm not entirely sure

const String msmqAccelaDev = "FormatName:DIRECT=OS:tcc-intsrvTCCIntegration.MSMQ.Service.Dev/TCCMessagingService.svc";
const String msmqAccelaProd = "FormatName:DIRECT=OS:tcc-intsrvTCCMSMQFail";
const String msmqAccelaTest = "FormatName:DIRECT=OS:tcc-intsrvTCCIntegration.MSMQ.Service.Test/TCCMessagingService.svc";
String currentQueue = "";
private void environmentChange()

[Code]...

View 4 Replies View Related

C++ :: Linked List Delete List?

May 30, 2013

I'm working on a linked list and was wondering how this looks to everybody else for a deleteList function.

void deleteList(Node* head)
{
Node* iterator = head;
while (iterator != 0)

[code].....

View 6 Replies View Related

C :: Insert Linked List Into Another Linked List

Jun 29, 2013

I have a linked list comprised of chars like so...

Code:

node1 - "p"
node2 - "o"
node3 - "p"

I need a function that will take in three perameters...node *replaceChar(node *head, char key, char *str)Stipulations of this function. head is the head of the list, 'key' and 'str' are guaranteed to contain alphanumeric characters only (A-Z, a-z, and 0-9). str can range from 1 to 1023 characters (inclusively). So if I call this function with these perameters..

Code:

node *head == /*the head of the list to be examined*/
char key == "p"char *str == "dog"The new list will look like this...
node1 - 'd'
node2 - 'o'
node3 - 'g'
node4 - 'o'
node5 - 'd'
node6 - 'o'
node7 - 'g'

All instances of 'p' were replaced with 'dog' I have a toString function which takes in a string and converts it to a linked list and returns the head. So assume that you can call the function on str = "dog" so...

Code:

toString(str) == /*this will return the head to the list made from the str*/

If it's unclear what my question is...I am stumped on how to write the replaceChar function the one that takes in three perameters..

View 3 Replies View Related

C :: Maintain A List

Apr 11, 2014

I want to maintain a list. which will update at regular interval. so I thought to with linked list. Earlier I have used linked list.

Code:

typedef struct
{
short nwkaddr;
unsigned char macaddress[8];
}device_t;
}

[code]....

This program is giving many errors. I tried lot to fix it. If I fix one then other bug is arising. for that I did't mentioned what bug i got.Main Issue is while (curr->next->list != NULL) this is giving segmentation fault if i add element second time

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved