2014-10-09 3 views
0

현재 Im 프로그래밍 원리 및 C++을 사용하는 관행 및 나는이 책에서 사용 된 오류 기능을 사용하는 방법을 잘 이해하지 못합니다.오류 기능 문제

함수는 std_lib_facilities에 포함

inline void error(const string& s) 
{ 
    throw runtime_error(s); 
} 

파일 헤더이다.

이것은 이것을 사용하는 작은 프로그램입니다.

int main() 
{ 
    cout << "Please enter expression (we can handle +, –, *, and /)\n"; 
    cout << "add an x to end expression (e.g., 1+2*3x): "; 
    int lval = 0; 
    int rval; 
    cin>>lval;                                     // read leftmost operand 
     if (!cin) error("no first operand"); 
     for (char op; cin>>op;) {          // read operator and right-hand operand 
                                                               // repeatedly 
      if (op!='x') cin>>rval; 
      if (!cin) error("no second operand"); 
      switch(op) 
      { 
       case '+': 
        lval += rval;               // add: lval = lval + rval 
        break; 
       case '–': 
        lval –= rval;               // subtract: lval = lval – rval 
        break; 
       case '*': 
        lval *= rval;           // multiply: lval = lval * rval 
        break; 
       case '/': 
        lval /= rval;            // divide: lval = lval/rval 
        break; 
       default:                           // not another operator: print result 
        cout << "Result: " << lval << '\n'; 
        keep_window_open(); 
        return 0; 
      } 
     } 
    error("bad expression"); 
} 

내 질문이 오류 함수가 오류를 잡기 위해 캐치가없는 경우 일을 생각하는 방법, 때 그 메시지가 표시 될 수 있도록 발생합니다.

+0

표시된 코드에서'error()'가 호출되면 프로그램이 중단 될 것입니다. 나는 이것이 정확하게 "일"이라는 용어의 의미에 해당한다고 생각하지 않을 것입니다. 아마 지금은 더 좋은 책을 찾기 시작하기에 좋은시기라고 말할 수 있습니다. –

+0

내가 기억 하듯이, Stroustrup은 머리말을 학습의 처음 몇 주 동안 사용할 수 있도록 디자인하여 나중에 시작하는 개념을 아직 알지 못해 쉽게 시작할 수 있습니다. 어쨌든 예외가 발견되지 않으면 구현시 메시지를 인쇄 할 수 있습니다. – chris

+0

'catch'가 없으면 프로그램이 종료됩니다. 컴파일러가 메시지를 표시할지 여부를 결정할 수도 있습니다. main 주위에 catch 핸들러를 추가 할 수 있습니다. –

답변

0

에 오류 메시지가 인쇄되도록하려면 구현 품질에 의존하지 말고 직접 수행해야합니다.

처럼,

#include <iostream>  // std::cout, std::cerr 
#include <stdexcept>  // std::runtime_error 
#include <stdlib.h>  // EXIT_FAILURE, EXIT_SUCCESS 
#include <string>  // std::string 
using namespace std; 

auto fail(string const& s) -> bool { throw runtime_error(s); } 

void cpp_main() 
{ 
    // What you would otherwise put directly in `main`, e.g. 
    cout << "x? "; 
    double x; 
    cin >> x 
     || fail("Uh oh, that was not a valid value for x."); 
} 

auto main() -> int 
{ 
    try 
    { 
     cpp_main(); return EXIT_SUCCESS; 
    } 
    catch(exception const& x) 
    { 
     cerr << "!" << x.what() << endl; 
    } 
    return EXIT_FAILURE; 
} 

면책 조항 : 컴파일러의 손에 의해 훼손되지 않은 코드입니다.


팁 : 무료 AStyle 포맷터를 사용하여 코드 형식을 수정할 수 있습니다.