2015-09-19 236 views
1

可能有人知道爲什麼這個try catch塊循環不起作用。我希望代碼每當用戶輸入一個字符串而不是一個數字,但它似乎並不想要的時候,就進入catch塊。嘗試catch塊不工作

x = 1; 
while x == 1 
    try 
     degree = input('Please enter the degree of the polynomial of interest: '); 
     if degree > 0 && degree <= 4 
      x = 0; 
     else 
      disp('Please Enter a degree from 1 to 4') 
     end 
    catch 
     exit = input('do you wish to exit (Y/N)','s'); 
     if strcmp(exit,'Y') 
      break 
     else 
      disp('Please enter an integer this time') 
     end 
    end 
end 
+0

老實說,我不知道try catch塊是否是實現你想要做的最好的方法。我會說在一個字符串中,使用'str2num'將其轉換爲數字。該函數還會返回一個狀態標誌,告訴您轉換是否成功。然後你可以循環。在這裏檢查:http://www.mathworks.com/help/matlab/ref/str2num.html – pragmatist1

+0

你可以在'try/catch'中調用'input()',不應該在'try/catch'並使用'try/catch'來驗證它是一個整數? (例如使用'mod(degree,1)' – Adriaan

回答

0

你還要來檢測錯誤條件(例如,如果輸入度不是整數),並拋出類型MException的一個例外,由catch塊被捕獲。

喜歡的東西:

x = 1; 
while x == 1 
    try 
     degree = input('Please enter the degree of the polynomial of interest: '); 
     if ~isa(degree,'integer') 
      ME = MException('MyFunction:notInteger', ... 
      'Variable %s not an integer',degree); 
      throw(ME) 
     end 
     if degree > 0 && degree <= 4 
      x = 0; 
     else 
      disp('Please Enter a degree from 1 to 4') 
     end 
    catch ME 
     exit = input('do you wish to exit (Y/N)','s'); 
     if strcmp(exit,'Y') 
      break 
     else 
      disp('Please enter an integer this time') 
     end 
    end 
end 

你可能想在你的catch塊額外的邏輯根據問題的具體情況做一些與捕獲的異常。