Try catch error function not working

조회 수: 10 (최근 30일)
Uyen Nguyen
Uyen Nguyen 2020년 9월 26일
댓글: Walter Roberson 2020년 9월 26일
I am having a hard time using the try catch error function to catch any negative input value for base (b) and height(h). I want to only take in positive value as input and takes the absolute value of the input if it's negative and an error message is displayed. Please help
if app.ShapeDropDown.Value == "Rectangle"
% taking in the dimensions of base and height
% Catching resulting errors if the input values are invalid
try
b = app.Dimension1EditField.Value;
h = app.Dimension2EditField.Value;
catch ME
if b < 0 | h <0
msgID = 'MATLAb:InvalidInput';
msg = 'Input for dimension(s) must be positive';
baseException = MException(msgID,msg);
baseException = addCause(baseException, causeExption);
b = abs(b);
h = abs(h);
end
% Calculate MOI
Ix = (b*(h^3))/12;
Iy = ((b^3)*h)/12;
% Displau the MOI on the table
d = {'Base',b, RegUnit;'Height',h,RegUnit;'Ix',Ix, CalcUnit;'Iy',Iy, CalcUnit'};
fig = uifigure('Position',[100 100 752 250]);
uit = uitable('Parent',fig,'Position',[25 50 700 200]);
uit.Data = d;
% Create axes for the figure. Axes of figure changes
% depending on base and height entered
app.UIAxes.XLim = [-1 b+1.00];
app.UIAxes.YLim = [-1 h+1.00];
%Polar axes
XX = linspace(b/2, Ix, 500);
YY = linspace(h/2, Iy, 500);
% % Create a vector that would span the X & Y direction
% positioned at the center of base and height
IXline = ones(1,500)*h/2;
IYline = ones(1,500)*b/2;
% Graph the rectangular shape on the axes
rectangle(app.UIAxes,'Position',[0 0 b h])
hold(app.UIAxes);%hold on
% plot the polar axes
plot(app.UIAxes,XX,IXline, 'r')
plot(app.UIAxes,IYline, YY, 'k')
hold(app.UIAxes,'off')
end

답변 (1개)

Cris LaPierre
Cris LaPierre 2020년 9월 26일
편집: Cris LaPierre 2020년 9월 26일
Your code must generate an error in the 'try' portion before it will execute what is in the catch. I don't see any reason why the current 'try' code should ever generate an error. Therefore, the code in 'catch' never runs.
Try looking at some of the examples in the try-catch documentation page.
  댓글 수: 1
Walter Roberson
Walter Roberson 2020년 9월 26일
That try/catch can produce an exception -- if app.Dimension1EditField.Value or app.Dimension2EditField.Value do not exist.
However, to have the catch invoked under the circumstance if b < 0 | h <0 then you would need to insert into the try section code such as
if b < 0 | h <0
error("values out of range");
end
and remove the "if" from the catch.
... But if you were going to do that, there would not be much point in doing so when you could simply put the if into the main code without any try/catch.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Graphics Performance에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by