簡體   English   中英

異常處理

[英]exception handling

我得到以下核心轉儲消息:

拋出'std :: out_of_range'實例之后的終止調用what():basic_string :: substr中止-核心轉儲

我正在從一個大文件中讀取一個14位十六進制數字。 定期地,我注意到有這些空行(嗯,我不確定這是什么。我該如何處理該異常?也許是嘗試捕獲的東西?它看起來像下面這樣:

123456789ABCDE
123456789ABCDE
123456789ABCDE

123456789ABCDE

我不確定哪個隱藏符號正在占用空間,但是會導致問題,並且我不確定如何處理此問題。 也許我可以獲得如何處理的樣本?

您需要發布更多代碼,但從例外來看,您似乎是逐行讀取文件並將該行存儲在std::string ,然后調用std::string::substr()提取所需的14個字符。

假設您的代碼如下所示:

std::string str;         /* the lines are stored in this string */
std::string substring;   /* extracted substring stored here */

/* Read file line by line */
// ...

substring = str.substr( index, 14 );  //extract 14 characters starting at 'index'

更改為:

if( str.size() > index ) {
  substring = str.substr( index, 14 );
}

在嘗試進行轉換之前,您可能需要包括輸入驗證。 切勿按原樣接受外部輸入,並始終進行驗證。

穩健性原則 (也稱為Postel定律):

保守發送的內容; 在接受的內容上保持自由。

因此,一種可能性就是忽略/跳過格式錯誤的行。

其他人給出了針對此特定問題的具體答案。

但通常在調試器中運行此命令,然后查看其拋出的位置。 對於gdb,請執行“ catch throw”,然后gdb將在錯誤所在的位置中斷。 原因很明顯。

以下代碼可能顯示了可能的問題:

#include <iostream>

int main(){
    std::string s = "Hi";

    std::string sb = s.substr(14, 0);  // extract 0 characters from 
                                       // an out-of-range 
                                       // start location
}

basic_string<charT,traits,Allocator>
substr(size_type pos = 0, size_type n = npos) const;

如果起始索引(第一個參數)無效(大於字符串對象的大小),則標准要求該方法拋出“ out_of_range”錯誤。

看起來您沒有使用try / catch進行字符串操作。 這不是一個好習慣。 在try catch塊中包含所有可能引發異常的代碼。 這使您有機會處理異常(如果您願意)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM