23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

8 Error Handling<br />

Handling and Recovering from an Error<br />

The catch segment of a try-catch block needs to effectively handle any<br />

errors that may be caught by the preceding try. Frequently, you will want<br />

to simply report the error and stop execution. This prevents erroneous data<br />

from being propagated into the remainder of the program.<br />

This section covers<br />

• “Reporting an Error” on page 8-4<br />

• “Identifying the Cause” on page 8-5<br />

• “Regenerating an Error” on page 8-8<br />

Reporting an Error<br />

To report an error and halt program execution, use the <strong>MATLAB</strong> error<br />

function. You determine what the error message will be by specifying it as an<br />

input to the error function in your code. For example,<br />

if n < 1<br />

error('n must be 1 or greater.')<br />

end<br />

displays the message shown below when n is equal to zero.<br />

??? n must be 1 or greater.<br />

Formatted Message Strings<br />

The error message string that you specify can also contain formatting<br />

conversion characters, such as those used with the <strong>MATLAB</strong> sprintf<br />

function. Make the error string the first argument, and then add any<br />

variables used by the conversion as subsequent arguments.<br />

error('formatted_errormsg', arg1, arg2, ...)<br />

Forexample,ifyourprogramcannotfind a specific file, you might report<br />

the error with<br />

error('File %s not found', filename);<br />

8-4

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!