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++
Click For 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.
  • #31
Regarding the code in post #20, this is what happens after you enter a number such as 3.
  1. fun1() is called in the try block.
  2. fun1() calls fun2().
  3. Since the argument is larger than 2, it throws 20.
  4. Control is transferred to the catch block, where it prints "Out of range."
  5. Control then goes to the next line, which prints "Program ends."
  6. main() then returns.
 
  • Like
Likes yungman
Technology news on Phys.org
  • #32
Mark44 said:
Regarding the code in post #20, this is what happens after you enter a number such as 3.
  1. fun1() is called in the try block.
  2. fun1() calls fun2().
  3. Since the argument is larger than 2, it throws 20.
  4. Control is transferred to the catch block, where it prints "Out of range."
  5. Control then goes to the next line, which prints "Program ends."
  6. main() then returns.
Yes, after I posted in post 17 and wasting my time on it, I decided this morning just write a program to proof in in post 20, it's exactly like what you layout here, it doesn't back track like the page in Ivor book page in post 17.

It doesn't matter how the program goes, it's more to find out whether I can trust the Ivor book. I read through it many times and I red line the sentences that support my assertion that the writing in the book does NOT match up to the drawings of the book. You can take a look at post 17.

thanks
 
  • #33
yungman said:
Thanks Jtbell

I ran your program step by step and label where the line jump to the next line. You can follow where the program goes. It NEVER return from fun2() back to fun1() and return back to try. That is exactly like what my program did. That's the whole point of my post 17. Here is your program with the steps added in comment:
C++:
#include<iostream>
using namespace std;

struct A
{
    ~A() {
        cout << "destroying A" << endl;// to 8
    }//to 40
};

struct E
{
    E() {}//to 21
    E(const E& other) {
        cout << "copy constructor E" << endl;// to 16
    }// to 7
};

void fun2(int b)//Never return back to fun1()
{//to 21
    if (b > 2) throw E();//to 13  to 15
}
void fun1(int a)
{//to 25
    fun2(a);//to 20
}

int main()
{
    int x = 5;// to 34

    try
    {
        A a;//to 35
        fun1(x);//to 24
        cout << "You entered: " << x << "\n\n";
    }
    catch (E e)
    {
        cout << "Out of range.\n\n";// to 41
    }// to 43

    cout << "Program ends.\n\n";// to 45

    return 0;
}

Thanks
This was about the things you claimed were wrong on the left side of the image you posted. The other thing you thought was wrong (from the right side of the image), I didn't follow exactly. I think you confused what the author was saying/showing.
 
  • #34
Jarvis323 said:
This was about the things you claimed were wrong on the left side of the image you posted. The other thing you thought was wrong (from the right side of the image), I didn't follow exactly. I think you confused what the author was saying/showing.
Oh, I have not even get to the left side yet. Let me go through that and get back to you. My book is still drying, it's not as if I have better things to do! :(

Read through the right side, I read it like 20 times. See whether I am wrong or not.
 
  • #35
yungman said:
Oh, I have not even get to the left side yet. Let me go through that and get back to you. My book is still drying, it's not as if I have better things to do! :(

Read through the right side, I read it like 20 times. See whether I am wrong or not.
I think the diagram is just a confusing diagram because of the clutter.

It says "Normal return" at the end of fun1(){} with an arrow that goes to after fun1(); is called. That means if an exception is NOT thrown, it goes there. The other arrow, says exception can be handled here, points directly from fun1() throw to the catch block.

This is the same as your program shows and as the book says, it's just easy to misread the diagram.
 
  • #36
Here is a somewhat cleaner version of the same diagram. Light blue is showing what happens if an exception is NOT thrown (normal return). I think in the book they could have left those arrows out, since it's more or less obvious. The red arrows show what happens when the exceptions are thrown.

I think you misread the blue arrows as if they are red arrows?

But yes, the diagram is pretty terrible (correct but terrible), so I don't blame you if you want to find a new book.

1611359248891.png
 

Attachments

  • 1611358924655.png
    1611358924655.png
    10 KB · Views: 160
  • #37
Jarvis323 said:
I think the diagram is just a confusing diagram because of the clutter.

It says "Normal return" at the end of fun1(){} with an arrow that goes to after fun1(); is called. That means if an exception is NOT thrown, it goes there. The other arrow, says exception can be handled here, points directly from fun1() throw to the catch block.

This is the same as your program shows and as the book says, it's just easy to misread the diagram.
I am saying the diagram on the right is correct, it's the writing on the page is incorrect.
 
  • #38
yungman said:
I am saying the diagram on the right is correct, it's the writing on the page is incorrect.
On the image you seemed to indicate it was wrong.

The writing is correct too I think. Maybe it's also just confusing language? What did you think was wrong about it exactly? Anyways, the writing was trying to explain what is shown in the diagram I posted. So if you understand that, you've got it and can move on. If the book you're using is too confusing, then maybe move on and try C++ primer.
 
  • #39
Jarvis323 said:
On the image you seemed to indicate it was wrong.

The writing is correct too I think. Maybe it's also just confusing language? What did you think was wrong about it exactly? Anyways, the writing was trying to explain what is shown in the diagram I posted. So if you understand that, you've got it and can move on. If the book you're using is too confusing, then maybe move on and try C++ primer.
This is a larger copy and I put red lines. I wrote how I read it. The diagram is correct as proven already, the writing is wrong.

It said the throw is not caught in fun3() ( because fun3() doesn't have a catch block), it will pass to the calling function fun1() ( also don't have a catch block) and should pass back to the one that called fun1() which is the Try block.

From fig.15.3 and both your program and my program, it jumped directly from fun2()( I called fun2() as fun3() in Fig.15.3) to the catch block.

I work with VS enough, if the function passes back to fun1(), it will step from fun3() to fun1() for sure. It did not.
 

Attachments

  • Ivor right.jpg
    Ivor right.jpg
    110.4 KB · Views: 151
  • #40
yungman said:
This is a larger copy and I put red lines. I wrote how I read it. The diagram is correct as proven already, the writing is wrong.

It said the throw is not caught in fun3() ( because fun3() doesn't not have a catch block), it will pass to the calling function fun1() ( also don't have a catch block) and should pass back to the one that called fun1() which is the Try block.

From fig.15.3 and both your program and my program, it jumped directly from fun2()( I called fun2() as fun3() in Fig.15.3) to the catch block.
Yeah, you just didn't understand. It IS CORRECT! LOL
 
  • #41
Jarvis323 said:
Yeah, you just didn't understand. It IS CORRECT! LOL
Like how? That's how I read it. Tell me how you read it.
 
  • #42
yungman said:
Like how?
It isn't saying how the control flow goes. It is explaining the propagation of the exception. Imagine the exception is like a baseball and it is flying past the next lines of code (which aren't being executed) yet, waiting to be caught. It is saying the ball does't just hit a wall at the end of a function, it keeps flying forward until eventually it is caught (then the control flow will go there where it is caught), or if nothing catches it, then program will terminate. The exception propagating doesn't mean the code it is skipping is executing.
 
  • Like
Likes Vanadium 50
  • #43
Jarvis323 said:
It isn't saying how the control flow goes. It is explaining the propagation of the exception. Imagine the exception is like a baseball and it is flying past the next lines of code (which aren't being executed yet, waiting to be caught). It is saying the ball does just hit a wall at the end of a function, it keeps flying forward until eventually it is caught (then the control flow will go there), or if nothing catches it, then program will terminate.
No it said it will pass back to the calling function. Like I said, I step through a lot of programs, if it pass through, VS will stop at the calling function even if it stop at the line with the last "}". VS do this every time. It never skip that.

If the book said it will go directly to the catch, then I have no problem with it.
 
  • #44
yungman said:
No it said it will pass back to the calling function. Like I said, I step through a lot of programs, if it pass through, VS will stop at the calling program even if it stop a the line with the last "}". VS do this every time. It never skip that.

If the book said it will go directly to the catch, then I have no problem with it.
You just didn't understand it. There's nothing at all more to it than that.
 
  • #45
Jarvis323 said:
You just didn't understand it. There's nothing at all more to it than that.
Sorry, I disagree. Like I said, I stepped through a lot of programs that call functions, even the function doesn't return anything, it will step back to the calling function after it finished.
 
  • #46
yungman said:
Sorry, I disagree. Like I said, I stepped through a lot of programs that call functions, even the function doesn't return anything, it will step back to the calling function after it finished.
You still obviously don't understand what it was attempting to convey. You can try reading it again, and read my comments, and if you still cannot understand it, just accept you don't get it, and try learning some other way.
 
  • #47
Jarvis323 said:
You still obviously don't understand what it was attempting to convey. What more is there to say. You can try reading it again, and read my comments, and if you still cannot understand, just accept you don't get it, and try learning some other way.
"An exception that is thrown but not caught within a function may be passed on to the calling function the next level up". This means if the exception is not caught in fun3(), it will passed on to the calling function fun1().

"Exception thrown by fun3() when it is called by fun1(). There is no try block in fun1(), so exceptions thrown by fun3() will be passed to the function that called fun1()." This means exactly what I said above. fun1() doesn't have a catch block either, so the exception is passed from fun1() back to try block.

Tell me which part do I not understand, please enlighten me.
 
  • #48
yungman said:
"An exception that is thrown but not caught within a function may be passed on to the calling function the next level up". This means if the exception is not caught in fun3(), it will passed on to the calling function fun1().

"Exception thrown by fun3() when it is called by fun1(). There is no try block in fun1(), so exceptions thrown by fun3() will be passed to the function that called fun1()." This means exactly what I said above.

Which part do I not understand, please enlighten me.
You're not understanding what the book was trying to explain. You're conflating the author's explanation of the propagation of the exception, with control flow.
 
  • Like
Likes Vanadium 50
  • #49
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.
 
  • #50
yungman said:
Well agree to disagree. I am very exact as this is science.
Maybe you can email the author and ask what he meant, and accuse him of making an error, and argue with him about if he is wrong or if you are wrong? I'm just trying to help.
 
  • #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
 
  • #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: 158
Last edited:

Similar threads

  • · Replies 30 ·
2
Replies
30
Views
4K
  • · Replies 118 ·
4
Replies
118
Views
9K
Replies
89
Views
6K
  • · Replies 35 ·
2
Replies
35
Views
4K
  • · Replies 89 ·
3
Replies
89
Views
6K
  • · Replies 19 ·
Replies
19
Views
2K
  • · Replies 39 ·
2
Replies
39
Views
5K
  • · Replies 5 ·
Replies
5
Views
3K
Replies
4
Views
2K
  • · Replies 66 ·
3
Replies
66
Views
6K