Problem with try/catch

조회 수: 17 (최근 30일)
Mahith Madhana Kumar
Mahith Madhana Kumar 2021년 3월 1일
댓글: Mahith Madhana Kumar 2021년 3월 1일
Hi all,
I am experiencing a problem with the try/catch function. When I run the below script:
x=1:1:10;
for i=1:length(x)
try
if (x(i)==5)
disp('Success');
end
catch
disp('Dot index error');
continue
end
end
I am only getting a single output corresponding to the part when x(i)==5. Its not displaying the "Dot index error" for other values. I am not sure where I am doing wrong.
I looked into this similar post - https://www.mathworks.com/matlabcentral/answers/108074-try-catch-problems-with-matlab-2013 but that didnt have any follow up answers.
Thank you your help.
  댓글 수: 2
Stephen23
Stephen23 2021년 3월 1일
"Its not displaying the "Dot index error" for other values."
I don't see any reason why it should: nothing in your code would obviously throw an error.
"I am not sure where I am doing wrong."
You are not doing anything wrong: nothing wrong means no error, which means no catch execution.
If no error occurs in your code, what error do you expect try to detect?
Mahith Madhana Kumar
Mahith Madhana Kumar 2021년 3월 1일
Oh yea. That makes sense. I was thinking the catch statement would be executed just like the else part of an if statement - my wrong. Thank you.

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

채택된 답변

KALYAN ACHARJYA
KALYAN ACHARJYA 2021년 3월 1일
편집: KALYAN ACHARJYA 2021년 3월 1일
Have you read the document of try catch Doc fucntion?
If any statement in a try block generates an error, program control goes immediately to the catch block, which contains your error handling statements.
x=5;
try
if x==5
kkdisp('Success');% Error undefined fucntion kkdisp
end
catch
disp('Dot index error');
end
What are you trying to do?
  댓글 수: 4
Mahith Madhana Kumar
Mahith Madhana Kumar 2021년 3월 1일
편집: Mahith Madhana Kumar 2021년 3월 1일
Can we achieve the same output using try/catch function?
KALYAN ACHARJYA
KALYAN ACHARJYA 2021년 3월 1일
It can be done anyway, its all about "Jugaad", is there any sense? The purpose of the function "Execute statements and catch resulting errors" (Error Handiling)
x=1:10;
for i=1:length(x)
try
if x(i)~=5
% Any Error syantax
HelloErrorHere
disp('Success');
else
disp('Success');
end
catch
disp('Dot index error');
end
end
Result:
Dot index error
Dot index error
Dot index error
Dot index error
Success
Dot index error
Dot index error
Dot index error
Dot index error
Dot index error
>>

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

추가 답변 (1개)

Mahith Madhana Kumar
Mahith Madhana Kumar 2021년 3월 1일
Thank you for the help.

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by