0
\$\begingroup\$

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.

\$\endgroup\$
2
  • 5
    \$\begingroup\$ I'm voting to close this question as off-topic because it is a question about programming with no specific application in electronics. \$\endgroup\$ Commented Apr 16, 2018 at 21:57
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ Commented Apr 16, 2018 at 22:55

1 Answer 1

2
\$\begingroup\$

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
\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.