c ++中的异常hadling [英] Exception hadling in c++

查看:120
本文介绍了c ++中的异常hadling的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



注意::抱歉这是非常基本的问题,如果你回复会很好



我想做什么是从文件中读取文本。用(:)分隔文本。但是如果文件中的某些行没有:比想要抛出错误。并且在catch部分显示msg错误的文本格式。

文件中的示例文本是

文本第1部分:文本第2部分//第1行

文本第1部分:文本第2部分//第2行

文本第1部分:文本第2部分//第3行

没有冒号的示例文本//第4行没有:



Hi
NOTE:: Sorry it is very basic question if you reply would be very nice

what i am trying to do is while reading text from file. splitting the text with ( : ). But if some line in the file has no : than want to throw error. and in the catch section display msg wrong text format.
sample text in file is
Text part 1 : Text Part 2 //line 1
text part 1 : text part 2 //line 2
text part 1 : text part 2 //line 3
sample text without colon //line 4 line without :

  try{
    QStringList Textfields = TextLine.split(":");
    TextFirstPart = Textfields [0];
    TextSecPart = Textfields [1];
throw;
}
catch(...)
{
cout <<"Unidntified Input data format"<<endl;
}



试图仅为第4行抛出错误信息。怎么做?



我尝试了什么:



i尝试了我上面提到的但它不起作用....


trying to throw error msg only for line 4. How to do this??

What I have tried:

i tried what i mentioned above but it is not working....

推荐答案

只需检查是否可以进行拆分。如果没有':'字符,则字符串不会被拆分,列表只包含一个元素(原始字符串):

Just check if splitting was possible. If there was no ':' character, the string is not splitted and the list contains only one element (the original string):
if (TextFields.count() == 1)
    throw;



但在您的情况下,不需要使用异常,因为您正在检测并处理函数内部的错误。相反,您可以使用错误指示器并从函数返回:


But in your case there is no need to use exceptions because you are detecting and handling the error inside your function. Instead you might use an error indicator and return that from your function:

int error = 0;
while (!error && !EndOfFile())
{
    QString TextLine = ReadLine();
    QStringList Textfields = TextLine.split(":");
    if (TextFields.count() == 1)
    {
        // No ':' character
        error = 1;
    }
    else if (TextFields.count() > 1)
    {
        // Multiple ':' characters
        error = 2;
    }
    // Check for other errors here
    else
    {
        // Process line
    }
}
if (error)
{
    // Show error message
}
// Return false when an error occured
return 0 == error;


为了使其正常工作,您应该删除 throw; 声明。无论如何,在这种简单的场景中你可以避免使用异常:使用 QStringList size 方法,你能够检测到'未识别的inpup数据格式'行。
In order to make it working, you should remove the throw; statement. In any case you might avoid using exceptions, in such a simple scenario: using the QStringList's size method, you are able to detect the 'unidentified inpup data format' line.


这篇关于c ++中的异常hadling的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆