尝试catch块不工作
问题描述:
可能有人知道为什么这个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
答
你还要来检测错误条件(例如,如果输入度不是整数),并抛出类型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块额外的逻辑根据问题的具体情况做一些与捕获的异常。
老实说,我不知道try catch块是否是实现你想要做的最好的方法。我会说在一个字符串中,使用'str2num'将其转换为数字。该函数还会返回一个状态标志,告诉您转换是否成功。然后你可以循环。在这里检查:http://www.mathworks.com/help/matlab/ref/str2num.html – pragmatist1
你可以在'try/catch'中调用'input()',不应该在'try/catch'并使用'try/catch'来验证它是一个整数? (例如使用'mod(degree,1)' – Adriaan