简体   繁体   中英

String throwing exception

I have the following code with two functions which should throw exceptions when condition is satisfied. Unfortunately the second one with string seems not working and I don't have a clue whats wrong

#include "iostream"
#include "stdafx.h"
#include "string"
using namespace std;
 
struct P
{
    int first;
    string second;
};
 
void T(P b)
{ if (b.first==0)
throw (b.first);
};
 
void U(P b)
{ if (b.second == "1, 2, 3, 4, 5, 6, 7, 8, 9" )
throw (b.second);
};
 
int _tmain(int argc, _TCHAR* argv[])
{
P x;
cin>>x.first;
cin>>x.second;
 
try
    {  
        P x;
        T(x);
    }
    catch (int exception)
    {
        std::cout << exception;
    }
 
    try{
        U(x);
    }
    catch (const char* exception)
    {
        std::cout << "\n" << exception;
    }
 
system("pause");
return 0;
}

I have the following input:

0
1, 2, 3, 4, 5, 6, 7, 8, 9

and the output:

0

and I want to get:

0
1, 2, 3, 4, 5, 6, 7, 8, 9

How can I change char for string output?

I do not know what you are trying to experiment, but despite being allowed by the language, throwing objects that are not instances of (subclasses of) std::exception should be avoided.

That being said you have a bunch of inconsistencies in your code.

First cin >> x.second; will stop at the first blank character . So in your example you have only "1," in x.second , so you test fails and you code does not throw anything.

You should ignore the newline left by cin >> x.first and use getline to read a full line include spaces:

P x;
cin >> x.first;
cin.ignore();
std::getline(cin, x.second);

The first try block invokes UB, because you are declaring a new x in that block that will hide the one you have just read. It should be:

try
{
    //P x;  // do not hide x from the enclosing function!
    T(x);
}

Finaly, and even it is not an error you should always catch non trivial object by const reference to avoid a copy. Remember that exceptions are expected to be raised in abnormal conditions, and when memory becomes scarce you should avoid copy. But you must catch the exact same object that was thrown. So the second catch should be:

catch (std::string exception)
{
    std::cout << "\n" << exception;
}

or better (avoid a copy):

catch (const std::string& exception)
{
    std::cout << "\n" << exception;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM