| View previous topic :: View next topic |
| Author |
Message |
sloppy Expert Cheater
Reputation: 0
Joined: 17 Aug 2008 Posts: 123
|
Posted: Sat Jan 03, 2009 7:37 pm Post subject: Exception handling |
|
|
| Code: | #include <iostream>
#include <string>
int main()
{
try
{
throw std::string("Hello, World?!").c_str();
}
catch (const char *e)
{
std::cout << e << '\n'; // Output: Nothing.
std::cout << ++e; // Output: ello, World?!
}
std::cin.sync();
std::cin.ignore();
return 0;
} |
Seems like the first character has been null terminated, but I'm not really sure why. Any thoughts?
|
|
| Back to top |
|
 |
crayzbeef Expert Cheater
Reputation: 0
Joined: 21 Jan 2007 Posts: 101
|
Posted: Sun Jan 04, 2009 3:32 pm Post subject: |
|
|
| Maybe because you're throwing a string and catching a char?
|
|
| Back to top |
|
 |
Heartless I post too much
Reputation: 0
Joined: 03 Dec 2006 Posts: 2436
|
Posted: Sun Jan 04, 2009 3:37 pm Post subject: |
|
|
_________________
What dosen't kill you, usually does the second time. |
|
| Back to top |
|
 |
DeletedUser14087 I post too much
Reputation: 2
Joined: 21 Jun 2006 Posts: 3069
|
Posted: Sun Jan 04, 2009 3:40 pm Post subject: |
|
|
That would be bizzare to check excpetion for.
Edit: instead of using sync and ignor to pause instant close, use cin.
|
|
| Back to top |
|
 |
Symbol I'm a spammer
Reputation: 0
Joined: 18 Apr 2007 Posts: 5094 Location: Israel.
|
Posted: Mon Jan 05, 2009 6:30 am Post subject: |
|
|
| crayzbeef wrote: | | Maybe because you're throwing a string and catching a char? |
He throws char*. (String.c_str())
That's pretty odd, but the problem is at c_str, since:
| Code: | try
{
throw "Hello, World!";
}
catch (const char *e)
{
std::cout << e << '\n'; // Output: Hello, World!
} |
Works perfectly fine.
You could also simply do:
| Code: | try
{
throw std::string("Hello, World!");
}
catch (std::string e)
{
std::cout << e.c_str() << '\n';
} |
|
|
| Back to top |
|
 |
sloppy Expert Cheater
Reputation: 0
Joined: 17 Aug 2008 Posts: 123
|
Posted: Mon Jan 05, 2009 5:08 pm Post subject: |
|
|
@Rot1
This is just a test case, not my actual code. You're bizarre.
@HornyAZNBoy, Symbol
Yea that is my current approach, though it would be nifty to throw a c string.
My best guess is that throw creates a copy of the char pointer (points to an internal buffer of string), which is then being cleaned up by the string object since it is no longer in use. If the string is defined outside the try block it works as you'd expect. D'oh.
|
|
| Back to top |
|
 |
|