MATLAB Basic matlab q on writing error messages

AI Thread Summary
Writing effective error messages in MATLAB involves clearly communicating the nature of the error when a function receives illogical input. A basic approach is to use simple print statements to inform the user of the issue, such as using fprintf to display an error message when conditions are not met. However, a more robust method is to utilize MATLAB's exception handling with MException. This allows for structured error management, enabling calling code to handle errors gracefully. By throwing an exception with a specific identifier and message, developers can provide clearer feedback about the input error, enhancing the overall user experience and debugging process.
brandy
Messages
156
Reaction score
0
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
 
Physics news on Phys.org
You could do something as basic as printing a string when the error occurs, e.g.:
Code:
function [output] = myfun(input)
    % do stuff
    if someCondition < minValue % define error condition however you need it
         fprintf('Error: invalid input. Input must be between foo and bar!\n');
         return;
    end
end

A better way would be to http://www.mathworks.com/help/techdoc/matlab_prog/bq_jgj8-1.html" . This way, any code that calls the function can handle errors.

Code:
function [output] = myfun(input)
    % do stuff
    if someCondition < minValue % define error condition however you need it
        err = MException('Myfun: Input Error', ...
                         'Myfun received bad input arguments.');
        throw(err);
    end
end
 
Last edited by a moderator:

Similar threads

Replies
4
Views
1K
Replies
2
Views
3K
Replies
5
Views
2K
Replies
5
Views
2K
Replies
2
Views
3K
Replies
1
Views
5K
Back
Top