if statement for error

조회 수: 28 (최근 30일)
Thijs Obers
Thijs Obers 2018년 6월 7일
댓글: Walter Roberson 2018년 6월 7일
Hi, is it possible to use an if-statement that responds wether an error occurs while running a script? and if the answer is yes, how can one achieve this?
here is a simple idea of what I mean
if error occurs
*do something*
end

채택된 답변

John D'Errico
John D'Errico 2018년 6월 7일
편집: John D'Errico 2018년 6월 7일
No. You cannot use if to find an error, because an error interrupts and stops execution of your code. However, you can use a try block to do that. Try intercepts any error that occur inside the try block, and immediately transfers execution into the catch block, where you can do as you wish.
try
a = 1:2;
a(5)
catch
disp('you did something wrong')
end
you did something wrong
So, when the try block executed, it assigned a to a vector of length 2. I can verify that a exists, and is of length 2.
a
a =
1 2
But then I did something silly, that will result in an error. Instead of allowing the error to be generated, it traps into the catch block, where I could have done whatever I wanted to, with the code continuing execution there.
No error message was generated. So, while I would have expected to see this:
a(5)
Index exceeds array bounds.
Instead, it dropped into the catch block. We can extract that error message, if we want to do so though.
lasterror
ans =
struct with fields:
message: 'Index exceeds array bounds.'
identifier: 'MATLAB:badsubscript'
stack: [0×1 struct]
So, you cannot use if. But you CAN use try/catch.
  댓글 수: 2
Thijs Obers
Thijs Obers 2018년 6월 7일
편집: Thijs Obers 2018년 6월 7일
so if I understand this correctly, try-catcht is basically an if-ifelse statement for errors?
Walter Roberson
Walter Roberson 2018년 6월 7일
try/catch is basically a GOTO for errors.

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by