2010-06-19 6 views

답변

32

std::exception에서 파생 경우 참조로 잡을 수 :

try 
{ 
    // code that could cause exception 
} 
catch (const std::exception &exc) 
{ 
    // catch anything thrown within try block that derives from std::exception 
    std::cerr << exc.what(); 
} 

그러나

예외가 std::exception에서 파생되지 않는 한 어떤 클래스 인 경우, 당신은 미리 유형을 알고 있어야합니다 (즉, std::string 또는을 잡아야합니다).).

당신은 캐치 모두 수행 할 수 있습니다

try 
{ 
} 
catch (...) 
{ 
} 

을하지만 당신은 제외하고 아무것도 할 수 없습니다.

+0

@R Samuel Klatchko : 감사합니다. 한 가지 더 질문합니다. 새 메소드와 삭제 메소드를 사용할 수 있습니까? – helloWorld

+0

@helloWorld - 그렇습니다.이 메소드는'new','delete' 그리고'new' 나'delete' 문이'try' 블록 안에 있다는 조건으로 호출되는 생성자 나 소멸자에서 던져진 예외를 잡아낼 것입니다. –

+3

std :: exception에서 예외가 파생되지 않은 경우 내 문제를 어떻게 해결해야합니까? – javapowered

1

먼저 R Samuel Klatchko의 제안대로 시도해보십시오. 도움이되지 않으면 다른 도움이 될 수 있습니다.

a) 디버거가 지원하는 경우 예외 유형 (처리됨 또는 처리되지 않음)에 중단 점을 배치하십시오.

b) 일부 시스템에서 컴파일러는 throw 문이 실행될 때 (문서화되지 않은?) 함수에 대한 호출을 생성합니다. 시스템에 어떤 기능이 있는지 알아 내려면 예외를 던지고 잡는 간단한 hello world 프로그램을 작성하십시오. 디버거를 시작하고 예외 생성자에 중단 점을 배치하고 호출되는 곳을 참조하십시오. caling 함수는 아마도 __throw()와 비슷할 것입니다. 그 후에 디버거로 조사하려는 프로그램으로 디버거를 다시 시작하십시오. 위에서 언급 한 함수 (__throw 또는 무엇이든)에 중단 점을 배치하고 프로그램을 실행합니다. 예외가 발생하면 디버거가 멈추고 바로 찾을 수 있습니다.

11

C++ 11에서 참조하십시오, 당신은 : 사이트에서 std::current_exception

예제 코드 :

이 헤더를 포함 : DAWID 할 Drozd 응답에서 영감을

#include <iostream> 
#include <string> 
#include <exception> 
#include <stdexcept> 

void handle_eptr(std::exception_ptr eptr) // passing by value is ok 
{ 
    try { 
     if (eptr) { 
      std::rethrow_exception(eptr); 
     } 
    } catch(const std::exception& e) { 
     std::cout << "Caught exception \"" << e.what() << "\"\n"; 
    } 
} 

int main() 
{ 
    std::exception_ptr eptr; 
    try { 
     std::string().at(1); // this generates an std::out_of_range 
    } catch(...) { 
     eptr = std::current_exception(); // capture 
    } 
    handle_eptr(eptr); 
} // destructor for std::out_of_range called here, when the eptr is destructed 
0

#include <exception>

try 
{ 
    // The code that could throw 
} 
catch(...) 
{ 
    auto expPtr = std::current_exception(); 

    try 
    { 
     if(expPtr) std::rethrow_exception(expPtr); 
    } 
    catch(const std::exception& e) //it would not work if you pass by value 
    { 
     std::cout << e.what(); 
    } 
} 
관련 문제