C/C++ Why does my program using cstring work while the one from the book doesn't?

  • Thread starter Thread starter yungman
  • Start date Start date
  • Tags Tags
    C++
AI Thread Summary
The discussion centers on a C++ programming issue where a program using a string literal fails to throw an exception correctly due to type mismatch. The original code throws a string literal, which is of type `const char*`, but the catch block expects a `char*`, leading to a runtime error. A modified version using a character array (`char Cr[]`) successfully throws and catches the exception. Participants suggest changing the catch statement to `catch (const char *e)` to resolve the issue, highlighting the importance of understanding const correctness in C++. The conversation also touches on frustrations with the instructional quality of the book being used, prompting a switch to a different C++ resource.
  • #51
Jarvis323 said:
Maybe you can email the author and ask what he meant, and argue with him about if he is wrong or if you are wrong? I'm just trying to help.
I think I'll wait for the new book I just ordered suggested by jbunniii .

Actually while I was stuck with that, I when back to Gaddis, actually after the first few pages, I followed right along and finished about 20 pages last night. So I am back to Gaddis again. I am almost finish with the exception, using class and all that. It is not that hard, Gaddis never talked about the process, only Ivor made a big sting how it jumps, so I want to make sure I follow right along. Now I see from everyone here confirming it jump all the way over to catch, it's not even a question anymore.

Anyway, thanks for your time, I apologize if I came out too strong. We both agree it fly over directly to the catch block, it's just how the book described. Too many books around to bother to write to the author. I don't enjoy wasting time to prove I am right or not. I just want to make sure I understand correctly, there is not any double we all agree about the program.

Thanks
 
Technology news on Phys.org
  • #52
yungman said:
Well agree to disagree. I am very exact as this is science.

This is actually like break, where you drop everything and just jump to the destination.
It's really confusing, as you are very unclear about what you think is wrong. But here is what I think I understand.

The book says the exception gets passed to the calling function if it's not caught in the function it's thrown from. And if it's not caught in the calling function, then it is passed to the next level (the calling function of the calling function, and so on). If it is never caught, then the program terminates.

It seems you thought the exception being passed along means the code is being executed or something (or the code is going where he describes the exception going). That is not the case.

The diagram agrees with the writing and that agrees with what your program does. Your misunderstanding is again confusing the authors description of the propagation of the exception with the execution of lines of code.
 
  • Like
Likes Vanadium 50, fluidistic and pbuk
  • #53
No, I don't mean when passing back to fun1(), meaning it has to execute something in fun1. It's like if fun1 call fun3, things got pushed onto stack( I don't mean your kind of stack, I mean stack pointer in processor to store the return address etc.). fun3 can just "stop" by fun1 to pop the stack pointer and fun1 back to try just to pop the stack pointer. Nothing is executed. So when the book describe like that, I expect the step will land back to fun1 and then to try even it doesn't execute any program lines. VS is very good in showing these steps even though no code is being executed.

What happens is it's literally calling a "BREAK" that you DROPPED everything and jump to catch block directly. This is what we agree on, not the normal way of returning back from a function that involves popping stacks. The way the book described, it's like step by step return back, not a fly ball flying over everything. In my low level assembly programming days, this is a very important distinction as direct jump is very different. I don't know how high level language handle the stack pointer, not popping the stack is dangerous.
 
  • #54
Unless of cause VS doesn't not show the temporary stop in this program. i don't know enough to see one way or the other. Maybe Mark44 who is the expert on VS can jump in. It is just my experience the VS is very good in jumping back to the calling function, even if it just landed on the empty closing bracket of the very last line of code "}". It just "stop by" for one stop!
 
  • #55
yungman said:
No, I don't mean when passing back to fun1(), meaning it has to execute something in fun1. It's like if fun1 call fun3, things got pushed onto stack( I don't mean your kind of stack, I mean stack pointer in processor to store the return address etc.). fun3 can just "stop" by fun1 to pop the stack pointer and fun1 back to try just to pop the stack pointer. Nothing is executed. So when the book describe like that, I expect the step will land back to fun1 and then to try even it doesn't execute any program lines. VS is very good in showing these steps even though no code is being executed.

What happens is it's literally calling a "BREAK" that you DROPPED everything and jump to catch block directly. This is what we agree on, not the normal way of returning back from a function that involves popping stacks. The way the book described, it's like step by step return back, not a fly ball flying over everything. In my low level assembly programming days, this is a very important distinction as direct jump is very different. I don't know how high level language handle the stack pointer, not popping the stack is dangerous.
I think you've got this wrong as well. This relates to the other thing (left side
of your image) you thought the book got wrong. That's why I posted code to demonstrate that the call stack is "popped" before the catch block.

Also, the stack we talk about in C++ is the same one you're talking about in assembly.
 
Last edited:
  • #56
@yungman yet again you are being pig-headed and insisting that only you are right and everybody else is wrong. I can see that, @Mark44 @Vanadium 50 @Jarvis323 @jtbell can see it, many other people reading this thread can see it but you cannot.

In the vain hope that reinforcement will 'enlighten' you, once more: the book does not say that control flow returns to fun1(). It says that "exceptions thrown by fun3() will be passed to the function that called fun1()".

yungman said:
I work with VS enough, if the function passes back to fun1(), it will step from fun3() to fun1() for sure. It did not.
VS follows control flow so yes, if control flow was passed back to fun1 then you would see it step back into fun1. But nobody is asserting that control flow is passed back to fun1.

yungman said:
Well agree to disagree. I am very exact as this is science.
You are exactly wrong and you need to understand and accept this.
 
Last edited:
  • Like
Likes fluidistic
  • #57
Here's an exercise in interpretation:

A train ticket that is bought on Tuesday but not used before midnight may be used on Wednesday. If it is not used on Wednesday it can be used the day after.

Does this say that the ticket was used on Wednesday?
 
  • #58
pbuk said:
Here's an exercise in interpretation:

A train ticket that is bought on Tuesday but not used before midnight may be used on Wednesday. If it is not used on Wednesday it can be used the day after.

Does this say that the ticket was used on Wednesday?
That said your writing is really bad, just like the book. If that's what you try to say, I would just say:

You can buy the ticket and USE it ANY DAY. Instead of going in circle to confuse people.

The book is NOT inventing anything, the point of the book is to make it very clear and easy to read and the book failed. All it has to say is fun3 will bypass everything and go straight to catch block. We won't be wasting time debate this.
 
  • #59
Here is some code you can use to check what happens with the stack.

C:
#include<iostream>
#include<string>
using namespace std;

struct A
{
    std::string name;
    A( const std::string & _name ) : name( _name ) {}
    ~A() {
        cout << "destroying " << name << endl;
    }
};

struct E
{
    E() {}
    E( const E & other ) {
        cout << "copy constructor E" << endl;
    }
};

void fun2( int b )
{
    A a2( "a2" );
    if (b > 2) throw E();
}
void fun1(int a)
{
    A a1( "a1" );
    fun2(a);
}

int main()
{ 
    int x = 5;

    try
    {
        A a0( "a0" );
        fun1( x );
        cout << "You entered: " << x << "\n\n";
    }
    catch( E e )
    {
        cout << "Out of range.\n\n";
    }
 
    cout << "Program ends.\n\n";
 
    return 0;
}

destroying a2
destroying a1
destroying a0
copy constructor E
Out of range.
 
  • Like
Likes pbuk
  • #60
Ok, this is regarding the page on the left side. The books said very clearly as red lined. See attachment

"Throwing an exception leaves the try block immediately, so at that point all the automatic objects that have been defined within the try block prior to the exception being thrown are destroyed".

Then: "It's also the reason why the exception object is copied in the throw process."

In order to be able to copy the exception object into temp, it has to by copied BEFORE destruction..

Look at fig. 15.2, It's is not clear what the number 1, 2, 3, 4 and 5 in the rectangular blocks stands for. Looked to be the order of events that is going to happen. So the event has to be:
1)Throw. which is labeled as 1 in fig. 15.2
2) Copy. which is labeled as 4 in fig 15.2.
3) destroy. which is labeled as 2.
4) Find first handler with a parameter type matching... labeled 3 and should start with catch(Type1 ex).
5)end.

So the writing is NOT the same as in Fig. 15.2.This is very important for people that is trying to learn. You go into detail, you cannot afford to make mistake.

Before you guys start calling me racist, I am Chinese from Hong Kong before AND I have lousy English. I think a lot of people in programming are minority and not good in English. BUT this is not an excuse to write a book with confusing description. When I was trying to publish papers in American Institute of Physics, my company actually got a technical writer to proof read my papers, made corrections and let me proof read before summited. This is NOT your own notes, this is for people to read and understand. Particular books, you are NOT publishing a new idea, the whole point of a book is to convey the information clearly to people that tries to learn. There is no innovation, no novel ideas, the only task is to explain clearly to people existing information. those people should know their limits and get a technical writer to proof read before publishing. There is no excuse for this.

I might be new in programming, but I am no stranger in studying books. I have 3 tall bookshelves of textbooks on physics, math, electronics, specialties books like Firewire, USB etal books that I studied, a lot of them from cover to cover through the years. I know how a good written book should be. I have more books in the subjects than the Stanford U library.
PS: Sorry the copy looks so awful, it is still drying and all wrinkled.
Look at my poor books, one chapter is cpt16 of Gaddis, the other is cpt 15 of Ivor.
Damage books.jpg
 

Attachments

  • Ivor6.jpg
    Ivor6.jpg
    98.7 KB · Views: 143
Last edited:
  • #61
yungman said:
It is just my experience the VS is very good in jumping back to the calling function
But your experience doesn't include working with exceptions, which can change the normal flow of control -- that's what they're supposed to do.

Again, and repeating what I said before and referring to the code in post #20, after the user enters a value out of range, such as 3, this is what happens.
  1. fun1() is called in main's try block.
  2. fun2() is called in fun1().
  3. fun2() throws an exception.
  4. The catch block prints " Out of range."
  5. The line right after the catch block prints " Program ends."
  6. The last line of the program executes.
Control does not return to fun1(), the function that called fun2(), so the normal flow of control is disrupted.
Control also does not return to the line right after the call to fun1() -- the program never prints " You entered."

You can verify the above by putting break points in select places, and noting that the break points don't get hit.
 
  • Like
Likes Vanadium 50 and pbuk
  • #62
Mark44 said:
But your experience doesn't include working with exceptions, which can change the normal flow of control -- that's what they're supposed to do.

Again, and repeating what I said before and referring to the code in post #20, after the user enters a value out of range, such as 3, this is what happens.
  1. fun1() is called in main's try block.
  2. fun2() is called in fun1().
  3. fun2() throws an exception.
  4. The catch block prints " Out of range."
  5. The line right after the catch block prints " Program ends."
  6. The last line of the program executes.
Control does not return to fun1(), the function that called fun2(), so the normal flow of control is disrupted.
Control also does not return to the line right after the call to fun1() -- the program never prints " You entered."

You can verify the above by putting break points in select places, and noting that the break points don't get hit.
I agree, I was saying the book is wrong in the writing. The fig 15.3 is absolutely correct.

In another words, what the book wrote in English is wrong. The fig 15.3 is absolutely correct as proven by my program tracking where the program goes step by step.

The throw in fun3() jumped straight to the catch block. Never gone through fun1() and try block at all. We all agree on that already.
 
Last edited:
  • #63
I am pretty much done with the exception part of the chapter of Gaddis. It is really quite simple. I can see Ivor book go deeper into nested of try, calling function with try-throw-catch inside function and all that.

Gaddis just talked a little about Rethrowing an Exception and don't even have an exercise program for it. The last one is handling bad_alloc for new operator that has a very small exercise program.

My question is whether learning what Gaddis covered is enough for exception? Here is the example of the most difficult program in Gaddis on exception. I actually put everything I learn in Gaddis into this program so you can see what Gaddis covered in the chapter:
C++:
#include <iostream>
using namespace std;
class Rectangle
{private: double width, length;
public:
    class NegativeW//exception class for -ve width
    { private:   int wid;
     public:
         NegativeW(int w) {wid = w;}
         int getW() const {return wid;}
    };
    class NegativeL//exception class for -ve length
    {private:     int len;
     public:
        NegativeL(int l) {len = l;}
        int getL() const {return len;}
    };
    Rectangle() //default constructor
    {   width = 0.0; length = 0.0;    }
    void setWidth(double w)
    {    if (w >= 0) width = w;
        else throw NegativeW(w);
    }
    void setLength(double len)
    {    if (len >= 0) length = len;
        else throw NegativeL(len);
    }
    double getWidth() const
        { return width;}
    double getLength() const
        { return length;}
    double getArea() const
        {return (width*length);}
};
int main()
{    double width, length;
    bool tryAgain = true;
    Rectangle myRect;
    cout<<" Enter the rectangle width: "; cin>>width; cout<<"\n";
    while(tryAgain)
    {
        try
        {    myRect.setWidth(width);//call Rectangle object myRect.setWidth()
            tryAgain = false;    //if width is +ve, set tryAgain = false to jump out
        }
        catch (const Rectangle::NegativeW negW)//argument is NegativeW object negL
        {    cout<<" You entered "<<negW.getW()<<" Enter +ve number: ";//re-enter a width
            cin>>width;
        }
    }//end while loop

    cout<<"\n Enter the rectangle length: ";
    cin>>length; cout<<"\n";
    tryAgain = true;//set to keep looping
    while(tryAgain)
    {
        try
        {    myRect.setLength(length);//call Rectangle object myRect.setWidth()
            tryAgain = false;//if length is +ve, set tryAgain = false to jump out
        }
        catch (const Rectangle::NegativeL negL)//argument is NegativeL object negL
        {    cout<<" You entered "<<negL.getL()<<" Enter +ve number: ";//re-enter a width
            cin>>length;
        }
    }//end while loop
    cout<<" The area of rectangle is: "<<myRect.getArea()<<"\n\n";
}

1) I put multiple exception using class object as exception object.
2) Using exception Handler to recover from errors ( ask to enter the right number over again)
3) Extract data from exception class(print out what was the input)

I am surprise that's all Gaddis covered in detail, I expect it would be more difficult. If this is enough, then I want to move on. Let me know what extra stuffs do I need to learn in the topic of Exception. Of cause, it's never enough, I just want a reasonable stopping point.

Next stop will be Template.

Thanks
 
Last edited:
  • #64
yungman said:
Ok, this is regarding the page on the left side. The books said very clearly as red lined. See attachment

"Throwing an exception leaves the try block immediately, so at that point all the automatic objects that have been defined within the try block prior to the exception being thrown are destroyed".

Then: "It's also the reason why the exception object is copied in the throw process."

In order to be able to copy the exception object into temp, it has to by copied BEFORE destruction..

Look at fig. 15.2, It's is not clear what the number 1, 2, 3, 4 and 5 in the rectangular blocks stands for. Looked to be the order of events that is going to happen. So the event has to be:
1)Throw. which is labeled as 1 in fig. 15.2
2) Copy. which is labeled as 4 in fig 15.2.
3) destroy. which is labeled as 2.
4) Find first handler with a parameter type matching... labeled 3 and should start with catch(Type1 ex).
5)end.

So the writing is NOT the same as in Fig. 15.2.This is very important for people that is trying to learn. You go into detail, you cannot afford to make mistake.

Before you guys start calling me racist, I am Chinese from Hong Kong before AND I have lousy English. I think a lot of people in programming are minority and not good in English. BUT this is not an excuse to write a book with confusing description. When I was trying to publish papers in American Institute of Physics, my company actually got a technical writer to proof read my papers, made corrections and let me proof read before summited. This is NOT your own notes, this is for people to read and understand. Particular books, you are NOT publishing a new idea, the whole point of a book is to convey the information clearly to people that tries to learn. There is no innovation, no novel ideas, the only task is to explain clearly to people existing information. those people should know their limits and get a technical writer to proof read before publishing. There is no excuse for this.

I might be new in programming, but I am no stranger in studying books. I have 3 tall bookshelves of textbooks on physics, math, electronics, specialties books like Firewire, USB etal books that I studied, a lot of them from cover to cover through the years. I know how a good written book should be. I have more books in the subjects than the Stanford U library.
PS: Sorry the copy looks so awful, it is still drying and all wrinkled.
Look at my poor books, one chapter is cpt16 of Gaddis, the other is cpt 15 of Ivor.
View attachment 276699
Did you not run my code and see that it shows that the writing was exactly correct, word for word, precisely? The order is as the author says it is, NOT the way you naively assumed it must be. You have a major problem understanding written language and concepts (no matter how clearly it's written), don't blame it on the authors.
 
Last edited:
  • Like
Likes pbuk
  • #65
Jarvis323 said:
Did you not run my code and see that it shows that the writing was exactly correct, word for word, precisely? The order is as the author says it is, NOT the way you naively assumed it must be. You have a major problem understanding written language and concepts (no matter how clearly it's written), don't blame it on the authors.
No! This is NOT about the program. It's about what is written doesn't match the figure. I am fine with whatever way is correct, it CANNOT be both correct.

I asked you how do you interpret the book if you don't agree, please don't call me naive. There's only very few sentences in the book that is relevant, READ every single one of them.

Tell me sentence by sentence what did I read wrong.
 
  • #66
yungman said:
No! This is NOT about the program. It's about what is written doesn't match the figure. I am fine with whatever way is correct, it CANNOT be both correct.

I asked you how do you interpret the book if you don't agree, please don't call me naive. There's only very few sentences, READ every single one of them.
What is written does match the text.

And yes, your insistence that the order the author says things happen in is wrong is very naive. It's also astounding that you're still claiming it's not correct when it's been demonstrated that YOU are WRONG, NOT the author.
 
  • Like
Likes pbuk
  • #67
Jarvis323 said:
What is written does match the text.

And yes, your insistence that the order the author says things happen in is wrong is very naive. It's also astounding that you're still claiming it's not correct when it's been demonstrated that YOU are WRONG, NOT the author.
NO, I SAID WHAT THE BOOK SAID DOES NOT MATCH IT'S OWN DRAWINGS. DON'T YOU EVEN READ? Just like the page on the right side.

Whether your program agree one way or the other is irrelevant.
 
  • #68
yungman said:
NO, I SAID WHAT THE BOOK SAID DOES NOT MATCH IT'S OWN DRAWINGS. DON'T YOU EVEN READ?
And you are WRONG. They do match. I did read it. And yes they match.
 
  • #69
Jarvis323 said:
And you are WRONG. They do match. I did read it. And yes they match.
Explain, how. You can start with the page on the right side. EXPLAIN how the writing match the fig 15.3.
 
  • #70
yungman said:
Explain, how. You can start with the page on the right side. EXPLAIN how the writing match the fig 15.3.
First of all, we were arguing about your naivety in assuming that figure 15.2 is wrong. Your comments on the page are wrong. The order the author gives is correct, and his writing matches the figure.

Second, we already went back and forth about your misunderstanding of the writing and of figure 15.3. Again you were WRONG. You pass the blame for your own inability to understand onto the author. You must just accept you're just flat WRONG and fix your understanding. You've got a lot to learn about humility.
 
  • Like
Likes Vanadium 50 and pbuk
  • #71
Jarvis323 said:
First of all, we were arguing about your naivety in assuming that figure 15.2 is wrong. Your comments on the page written are wrong. The order the author gives is correct, and his writing matches the figure.

Second, we already went back and forth about your misunderstanding of the writing and of figure 15.3. Again you were WRONG. You pass the blame for your own inability to understand onto the author. You must just accept you're just flat WRONG and fix your understanding. You've got a lot to learn about humility.
No, You only insult, you have not explain ANYTHING. Read post 39, 47 and 60, tell we how I read it wrong. How the writing match the drawings? Which sentence I interpreted wrong? there's only a few sentences in question IF YOU JUST STOP AND READ IT.

Or else there is no point in talking about this anymore. It just going to get ugly. Until you can point out each sentence how it match the drawing, there's no point in talking and I stand by my conclusion.

For cry out loud, these are very simple stuffs, either one way is right or the other.
 
  • Sad
Likes Dale
  • #72
yungman said:
No, You only insult, you have not explain ANYTHING. Read post 39, 47 and 60, tell we how I read it wrong. How the writing match the drawings? Which sentence I interpreted wrong?

Or else there is no point in talking about this anymore. It just going to get ugly. Until you can point out each sentence how it match the drawing, there's no point in talking and I stand by my conclusion.

For cry out loud, these are very simple stuffs, either one way is right or the other.
Are you kidding me? I rephrased the authors writing in a way to try to help you understand it, and explained what the author's language means, I remade the figure to make it more understandable, I rewrote your program so that it would show you the order of the objects destroyed and the copy of the exception. I've answered all of your questions in detail.

What more can you ask for?

It is pretty nice I even went out of my way to read your incoherent post and tried reading your photocopied image that I needed to zoom in on and squint at.

I would be surprised if you actually even read what I've written, and if you have I don't know how in the world you still don't get it.

You asked if the book was wrong, and it isn't. If you're unable to accept that, then why did you ask us in the first place? You just like wasting our time?
 
  • Like
Likes Dale, Vanadium 50 and pbuk
  • #73
yungman said:
That said your writing is really bad, just like the book. If that's what you try to say, I would just say:

You can buy the ticket and USE it ANY DAY. Instead of going in circle to confuse people.
But that would be wrong: you can't use the ticket any day, you can only use the ticket on Thursday if you have not already used it on Tuesday or Wednesday.

yungman said:
All it has to say is fun3 will bypass everything and go straight to catch block.
And this would also be wrong; if this happened then the return address and calling parameters from fun2 would be left on the stack and the program would crash. The critical point that you need to understand is that the exception bubbles up through the call stack until it is handled by a catch block (or if there is no catch block in the stack dealt with as an uncaught exception).
 
  • Like
Likes Vanadium 50 and Jarvis323
  • #74
yungman said:
Before you guys start calling me racist

Nobody called you racist. Insinuating that they did is not very nice.

To get back on track, the example in Gaddis is OK for showing how exceptions work, but it is not a very good guide on when to use them.

The reason exceptions exist is to separate error handling code from normal operation code. There is nothing that exceptions do that cannot be done using other C++ features, but using exceptions let's you do this in a way that the program logic is cleaner.

The Gaddis example checks that the input of a positive number is in fact positive. I would call this "validation", and I would claim that good coding practice is to reject the input if you know it is bad and to let the user try again at that point, rather than throwing an exception.

Using try/throw/catch to do bounds checking at the point of input is like using a sledgehammer to kill an ant. An ant standing on a very expensive watch.
 
  • Like
Likes fluidistic
Back
Top