0

I am trying to handle exceptions gracefully such that when a user enters a character, when a number is expected, he is notified with a custom warning/message.

I know that the try, catch has the following syntax:

try
   statements
catch exception
   statements
end

I have been trying something like this, to no avail:

number = input('Enter number'); 
try
    assert(isnumeric(number));
catch ME
    warning('NOT A NUMBER');
end

I do not understand why the above code fails since assert if it is false, displays the error message 'Assertion Failed'.

I know that using try and catch is a bit of a sledgehammer approach, but I would like to understand how to implement the above functionality. Any tips would be appreciated.

rrz0
  • 1,171
  • 1
  • 21
  • 42
  • 5
    I'm voting to close this question as off-topic because it is a question about programming with no specific application in electronics. – The Photon Apr 16 '18 at 21:57
  • 1
    A better way would be to use number(number==isnan(number))=0; or some other real value which would set all numbers in the vector that are NaN's to 0 – Voltage Spike Apr 16 '18 at 22:55

1 Answers1

2

because assert requires a user message when the assert occurs THEN the try/catch will work

You want something like this:

a = 'a';
try
    assert(isnumeric(a),'Not a number AAAA');

catch foo
    warning('Not a number');
end
1+1

As you can see the assert message is caught and the user WARNING is shown.

Alternatively you can use a function that will fail on non-number to remove the need of assert.

a = 'a';
try
    mustBeNumeric(a)

catch foo
    warning('Not a number');
end
1+1