Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Basic matlab q on writing error messages

  1. Aug 31, 2011 #1
    How do you write error messages
    for when a function has been given an input that is illogical for what the function does.
    in matlab

    function b = bla(a)
    for example if a < 0
    i want it to display a message
     
  2. jcsd
  3. Aug 31, 2011 #2

    jhae2.718

    User Avatar
    Gold Member

    You could do something as basic as printing a string when the error occurs, e.g.:
    Code (Text):

    [COLOR="Blue"]function[/COLOR] [output] = myfun(input)
        [COLOR="SeaGreen"]% do stuff[/COLOR]
        [COLOR="blue"]if[/COLOR] someCondition < minValue [COLOR="SeaGreen"]% define error condition however you need it[/COLOR]
             fprintf([COLOR="Indigo"]'Error: invalid input. Input must be between foo and bar!\n'[/COLOR]);
             [COLOR="blue"]return[/COLOR];
        [COLOR="blue"]end[/COLOR]
    [COLOR="Blue"]end[/COLOR]
     
    A better way would be to http://www.mathworks.com/help/techdoc/matlab_prog/bq_jgj8-1.html" [Broken]. This way, any code that calls the function can handle errors.

    Code (Text):

    [COLOR="Blue"]function[/COLOR] [output] = myfun(input)
        [COLOR="SeaGreen"]% do stuff[/COLOR]
        [COLOR="blue"]if[/COLOR] someCondition < minValue [COLOR="SeaGreen"]% define error condition however you need it[/COLOR]
            err = MException([COLOR="Indigo"]'Myfun: Input Error'[/COLOR], [COLOR="Navy"]...[/COLOR]
                             [COLOR="Indigo"]'Myfun received bad input arguments.'[/COLOR]);
            throw(err);
        [COLOR="blue"]end[/COLOR]
    [COLOR="Blue"]end[/COLOR]
     
     
    Last edited by a moderator: May 5, 2017
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Basic matlab q on writing error messages
Loading...