Continue with script despite an absent variable (error)?

4 views (last 30 days)
Hello, so I have a script that analyzes several variables on a truck (such as engine speed, GPS coordinates, etc.), and it makes sure the variables are within a certain range and that they exist. One of our variables, DPF temperature, is often absent, and I am wondering if there is a way to continue running my script even though Matlab shows an error saying the DPF temp variable does not exist? Here is the DPF temp code...
if exist('CAN2_THMM_03158_MSG0_DPF_INLET')==0; %#ok<EXIST>
disp('--An error has occurred in "CAN2_THMM_03158_MSG0_DPF_INLET" - Data does not exist.');
else
x = min(CAN2_THMM_03158_MSG0_DPF_INLET);
y = max(CAN2_THMM_03158_MSG0_DPF_INLET);
if any( y > 800 | x < -25)
disp('--An error has occurred in "CAN2_THMM_03158_MSG0_DPF_INLET" - Data outside accepted range.');
end
Matlab will recognize that 'CAN2_THMM_03158_MSG0_DPF_INLET' does not exist, and it will show an error and stop the entire script. How do I prevent this?

Accepted Answer

kjetil87
kjetil87 on 7 Aug 2013
I cannot see why matlab would throw an error with "do not exist" from your code, since you have already checked that 'CAN2_THMM_03158_MSG0_DPF_INLET' exists, and from the code you posted here there is nothing being done with the variable if it does not exist. A scary thing about the exist function and comparing it to zero is that exists can return a nonzero value say e.g if 'CAN2_THMM_03158_MSG0_DPF_INLET' is a file or something else (see help exist) .
I would recommend using :
exist('CAN2_THMM_03158_MSG0_DPF_INLET' , 'var' )
if it is a variable. Its both faster and safer.
With that being said, if there is a code you are unsure about that can produce errors that you want to handle manually you can surround it in a
try
catch
block.
for instance this code:
try
test=5+5;
test(1)=test(1)+test(2);
catch ME
fprintf('an error as occured: %s\n',ME.message)
end
will produce :
an error as occured: Attempted to access test(2); index out of bounds because numel(test)=1.
But it will not stop your script. From your copy paste code you are also missing an
end
after the
if any( y > 800 | x < -25)
disp('--An error has occurred in "CAN2_THMM_03158_MSG0_DPF_INLET" - Data outside accepted range.');
statement.
If you post the exact error message you get and the code line that is responsible it will be easier to help you further. For instance it is not clear what type of variable "CAN2_THMM_03158_MSG0_DPF_INLET" is. For instance if it is a structure with multiple fields you may need to check that each field exists and that they are not empty.

More Answers (0)

Categories

Find more on Performance and Memory in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!