2016-12-04 1 views
0

내 코드에서 예외 처리를 사용하여 무한 루프를 제거하려고 시도했으나 작동하지 않는 사람이이 스 니펫을 살펴보고 내가 잘못 했니? 그들은 먼저 발생하는 경우C++ while 루프에서 타이핑 오류를 해결하기 위해 예외 처리를 수행하는 방법

void Addition(float num) 
 
\t { 
 
\t \t 
 
\t \t cout<<"Please enter number you wish to add:"<<endl; 
 
\t \t cin>>num; 
 
\t \t 
 
\t \t while(num!=-9999) 
 
\t \t { 
 
\t \t \t Sum+=num; 
 
\t \t \t cout<<"Sum is:"<<Sum<<endl; 
 
\t \t \t cout<<"Please enter number or enter -9999 to exit"<<endl; 
 
\t \t \t try{ 
 
\t \t \t \t cin>>num; 
 
\t \t \t } 
 
\t \t \t catch(...) 
 
\t \t \t {cout<<"ERROR"<<endl; 
 
\t \t \t } 
 
\t \t 
 
\t \t \t 
 
\t \t } 
 
\t \t 
 
\t \t 
 
\t }

+1

catch 블록의 끝에 있지만 내부에는'num = -9999;를 추가하십시오. 아니면 그냥 끝내고 싶은 메시지를 출력해라. -9999 – doug

+0

예외는 while 루프 안에서 잡히고 실행은 계속된다. 예외가'while' 루프를 종료 시키길 원한다면, 루프 밖에서 try/catch를 가져야 만합니다. 전체 while 루프는'try' 블록 안에 있어야합니다. –

+0

* 마법 번호 *를 사용하지 마십시오. 누군가가'-9999'를 합계에 추가해야한다면? 이것이'eof()'신호가있는 것이다. – tadman

답변

1

예외는 붙잡힌 다. 코드의 어떤 부분도 throw 키워드를 사용하여 예외를 throw하지 않습니다. 그러나 당신은 당신이 당신의 의도

의 경우 break 문을 사용하여 루프를 종료 할 필요가 귀하의 catch 블록뿐만 아니라 루프에 있어야한다는 것을 할 경우에도 다음과 같은

void Addition(float num) 
    { 
     int Sum=0; 
     cout<<"Please enter number you wish to add:"<<endl; 
     cout<<"Please enter number or enter -9999 to exit"<<endl; 

     while(true) // whcih actually makes it infinite 
     { 
      try{ 
       cin>>num; 
       if(num == -9999) 
        throw -9999; // you can throw any value in this case 
       Sum+=num; 
      } 
      catch(...) 
      { 
      cout <<" ABORTING.."<<endl; 
      break; 
      } 
     } 

     cout << "Sum is:" << Sum << endl; 
    } 

위의 코드는 할 수 이처럼 간단히 할 수있는 것은 불필요합니다.

void Addition(float num) 
     { 
      int Sum=0; 
      cout<<"Please enter number you wish to add:"<<endl; 
      cout<<"Please enter number or enter -9999 to exit"<<endl; 

      while(true) // whcih actually makes it infinite 
      { 

        cin>>num; 
        if(num == -9999) 
        { 
         cout << "ABORTING.." << endl; 
         break; 
        } 

        Sum+=num; 
      } 

      cout << "Sum is:" << Sum << endl; 
     } 
+1

더 나은 :'while (std :: cin >> num && num! = -9999)'. –

관련 문제