2016-08-29 6 views
8

प्रसंग पर संभाला नहीं है

मैं इस सरल कोड है:अपवाद fstream खुला

g++ -std=c++11 -g // ... 

संकलक के संस्करण है:

#include <iostream> 
#include <fstream> 
#include <system_error> 

int main(int argc, char *argv[]) { 
    std::ifstream file; 
    file.exceptions(std::ios::failbit | std::ios::badbit); 

    try { 
    file.open("a_file_does_not_exist.txt", std::ios::in); 
    file.close(); 
    } catch(const std::ios_base::failure& err) { 
    std::cerr << err.code() << std::endl; 
    return -1; 
    } 

    return 0; 
} 

बस पूरा करने के लिए, इस आदेश का संकलन है जी ++ (जीसीसी) 6.1.1

प्लेटफ़ॉर्म: आर्क-लिनक्स 4.7.2-1


समस्या

आप कल्पना कर सकते हैं, फ़ाइल मौजूद नहीं है तो विधि file.open(...) एक अपवाद फेंक देते हैं। समस्या यह है कि जब मैं कोड चलाता हूं तो एक अपवाद को नियंत्रित नहीं किया जाता है, और std::terminate कहा जाता है।

अजीब बात आउटपुट है:

terminate called after throwing an instance of 'std::ios_base::failure' 
    what(): basic_ios::clear 
Annullato (core dump creato) 

आप पढ़ सकते हैं के रूप में, फेंक वर्ग एक std::ios_base::failure है, लेकिन मेरे पकड़ सही है कि वर्ग है।

मेरा सवाल है: मुझे क्या याद आ रही है?

+4

[पुष्टि] (http://coliru.stacked-crooked.com/a/81a72462c322e96f) –

+0

संभवतः संबंधित: http://stackoverflow.com/questions/35088800/what-effect-would-lwg2349-have/35089910 # 3508 9910 –

+4

जी ++ 5.4.0 –

उत्तर

-1

अपवाद हैंडलिंग के लिए आप file.good() और file.fail() का उपयोग क्यों नहीं करते हैं। यह आप जो करने की कोशिश कर रहे हैं उसके लिए यह पूरी तरह से काम करेगा।

संबंधित मुद्दे