Main Content
Generate, catch, and respond to warnings and errors
To make your code more robust, check for edge cases and problematic
conditions. The simplest approach is to use an if
or
switch
statement to check for a specific condition,
and then issue an error or warning. try/catch
statements
allow you to catch and respond to any error.
MATLAB Language Syntax
try, catch |
Execute statements and catch resulting errors |
Functions
error |
Throw error and display message |
warning |
Display warning message |
lastwarn |
Last warning message |
assert |
Throw error if condition false |
onCleanup |
Cleanup tasks upon function completion |
Topics
- Issue Warnings and Errors
To flag unexpected conditions when running a program, issue a warning. To flag
fatal problems within the program, throw an error. Unlike warnings, errors halt
the execution of a program. - Suppress Warnings
Your program might issue warnings that do not always adversely affect
execution. To avoid confusion, you can hide warning messages during execution by
changing their states from'on'
to
'off'
. - Restore Warnings
You can save the warning current states, modify warning states, and restore
the original warning states. This technique is useful if you temporarily turn
off some warnings and later reinstate the original settings. - Change How Warnings Display
You can control how warnings appear in MATLAB®, including the display of warning suppression information and
stack traces. - Use try/catch to Handle Errors
Use a
try/catch
statement to execute code after your
program encounters an error. - Clean Up When Functions Complete
It is a good programming practice to leave your program environment in a clean
state that does not interfere with any other program code.
Overview
The MATLAB® software, by default, terminates the currently running program when an
exception is thrown. If you catch the exception in your program, however, you can
capture information about what went wrong and deal with the situation in a way that
is appropriate for the particular condition. This requires a
try/catch
statement.
The try/catch Statement
When you have statements in your code that could generate undesirable results, put
those statements into a try/catch
block that catches any errors
and handles them appropriately.
A try/catch
statement looks something like the following
pseudocode. It consists of two parts:
-
A
try
block that includes all lines between the
try
andcatch
statements. -
A
catch
block that includes all lines of code between
thecatch
andend
statements.
try Perform one ... or more operations A catch ME Examine error info in exception object ME Attempt to figure out what went wrong Either attempt to recover, or clean up and abort end B Program continues
The program executes the statements in the try
block. If it
encounters an error, it skips any remaining statements in the
try
block and jumps to the start of the
catch
block (shown here as point A
). If
all operations in the try
block succeed, then execution skips
the catch
block entirely and goes to the first line following
the end
statement (point B
).
Specifying the try
, catch
, and
end
commands and also the code of the
try
and catch
blocks on separate lines is
recommended. If you combine any of these components on the same line, separate them
with commas:
try, surf, catch ME, ME.stack, end
ans =
file: 'matlabroottoolboxmatlabgraph3dsurf.m'
name: 'surf'
line: 49
Note
You cannot define nested functions within a try
or
catch
block.
The Try Block
On execution, your code enters the try
block and executes
each statement as if it were part of the regular program. If no errors are
encountered, MATLAB skips the catch
block entirely and continues
execution following the end
statement. If any of the
try
statements fail, MATLAB immediately exits the try
block, leaving any
remaining statements in that block unexecuted, and enters the
catch
block.
The Catch Block
The catch
command marks the start of a
catch
block and provides access to a data structure that
contains information about what caused the exception. This is shown as the
variable ME
in the preceding pseudocode.
ME
is an MException
object. When an
exception occurs, MATLAB creates an MException
object and returns it in
the catch
statement that handles that error.
You are not required to specify any argument with the catch
statement. If you do not need any of the information or methods provided by the
MException
object, just specify the
catch
keyword alone.
The MException
object is constructed by internal code in
the program that fails. The object has properties that contain information about
the error that can be useful in determining what happened and how to proceed.
The MException
object also provides access to methods that
enable you to respond to the exception.
Having entered the catch
block, MATLAB executes the statements in sequence. These statements can attempt
to
-
Attempt to resolve the error.
-
Capture more information about the error.
-
Switch on information found in the
MException
object and respond appropriately. -
Clean up the environment that was left by the failing code.
The catch
block often ends with a
rethrow
command. The rethrow
causes MATLAB to exit the current function, keeping the call stack information
as it was when the exception was first thrown. If this function is at the
highest level, that is, it was not called by another function, the program
terminates. If the failing function was called by another function, it returns
to that function. Program execution continues to return to higher level
functions, unless any of these calls were made within a higher-level
try
block, in which case the program executes the
respective catch block.
Suggestions on How to Handle an Exception
The following example reads the contents of an image file. It includes detailed
error handling, and demonstrates some suggested actions you can take in response to
an error.
The image-reading function throws and catches errors in several ways.
-
The first
if
statement checks whether the function is
called with an input argument. If no input argument is specified, the
program throws an error and suggests an input argument to correct the
error. -
The
try
block attempts to open and read the file. If
either the open or the read fails, the program catches the resulting
exception and saves theMException
object in the variable
ME1
. -
The
catch
block checks to see if the specified file
could not be found. If so, the program allows for the possibility that a
common variation of the filename extension (e.g.,jpeg
instead ofjpg
) was used, by retrying the operation with
a modified extension. This is done using atry/catch
statement nested within the originaltry/catch
.
function d_in = read_image(filename) % Check the number of input arguments. if nargin < 1 me = MException('MATLAB:notEnoughInputs','Not enough input arguments.'); aac = matlab.lang.correction.AppendArgumentsCorrection('"image.png"'); me = me.addCorrection(aac); throw(me); end % Attempt to read file and catch an exception if it arises. try fid = fopen(filename,'r'); d_in = fread(fid); catch ME1 % Get last segment of the error identifier. idSegLast = regexp(ME1.identifier,'(?<=:)w+$','match'); % Did the read fail because the file could not be found? if strcmp(idSegLast,'InvalidFid') && ... ~exist(filename,'file') % Yes. Try modifying the filename extension. switch ext case '.jpg' % Change jpg to jpeg filename = strrep(filename,'.jpg','.jpeg'); case '.jpeg' % Change jpeg to jpg filename = strrep(filename,'.jpeg','.jpg'); case '.tif' % Change tif to tiff filename = strrep(filename,'.tif','.tiff'); case '.tiff' % Change tiff to tif filename = strrep(filename,'.tiff','.tif'); otherwise fprintf('File %s not foundn',filename); rethrow(ME1); end % Try again, with modified filenames. try fid = fopen(filename,'r'); d_in = fread(fid); catch ME2 fprintf('Unable to access file %sn',filename); ME2 = addCause(ME2,ME1); rethrow(ME2) end end end
This example illustrates some of the actions that you can take in response to an
exception.
-
Compare the
identifier
field of the
MException
object to possible causes of the error. In
this case, the function checks whether the identifier ends in
'InvalidFid'
, indicating a file could not be
found. -
Use a nested
try/catch
statement to retry the operation
with improved input. In this case, the function retries the open and read
operations using a known variation of the filename extension. -
Display an appropriate message.
-
Add the first
MException
object to the
cause
field of the second. -
Add a suggested correction to an
MException
object. -
Rethrow the exception. This stops program execution and displays the error
message.
Cleaning up any unwanted results of the error is also advisable. For example,
close figures that remained open after the error occurred.
При
обнаружении ошибок в выражениях или
командах MATLAB указывает на наличие
ошибки. Из текста иногда можно понять
сущность ошибки, но часто комментарии
бывают настолько общими, что трудно
установить место и содержание ошибки.
Надо отличать предупреждение
об ошибке от сообщения
о ней. Предупреждения
(обычно после слова Warning)
не останавливают вычисления и лишь
предупреждают о том, что ответ может
быть ошибочным.
Пример
предупреждения:
>>
sin(0)/0
Warning:
Divide
by
zero.
ans =
NaN
При
сообщении
об ошибке красного
цвета
(после
знаков ???) MATLAB не выдает решение. Вычислим,
например, значение с помощью встроенной
элементарной функции sqrt
(квадратный корень), введя выражение
>>
sqr(2)
???
Undefined function or variable ‘sqr’.
Это
сообщение об ошибке говорит о том (на
английском языке), что не определена
функция или переменная и указывает на
sqr.
Устранение
ошибки наиболее целесообразно не путем
набора нового правильного выражения,
а редактированием ошибочного.
Существует несколько
способов возврата в строку ввода ранее
введенных команд.
Первый
способ
– с помощью клавиш <↑>
и <↓>
(см. разд. 1.2).
При
вычислении значения обнаружена
синтаксическая
ошибка:
не определена функция sqr.
Клавишей <↑> вернем команду >>
sqr(2) в командную строку. Отредактируем
ее: после sqr
вставим t
и нажмем клавишу <Enter>:
>> sqrt(2)
ans =
1.4142
Второй
способ
– копирование из окна Command
History.
Для
активизации окна Command
History
необходимо
войти в меню View
командного
окна, выбрать
вкладку с одноименным названием и
щелкнуть на ней левой кнопкой мыши
(поставить галочку). В этом окне
отображаются дата и время каждого сеанса
работы в MATLAB, а также перечень команд,
вводимых в течение каждого сеанса (рис.
1.4).
Если
в окне Command
History
дважды щелкнуть левой кнопкой мыши на
какой – либо команде, эта команда будет
выполнена. Это равнозначно вводу данной
команды в командное окно и последующему
нажатию клавиши <Enter>
(рис. 1.4).
Рис. 1.4
Если
щелкнуть на какой – либо команде окна
Command
History
левой
кнопкой мыши, то данная команда становится
текущей (на синем фоне). Можно выделить
нужную последовательность команд при
помощи комбинации клавиш <Shift>+<↑>,
<Shift>+<↓>.
При щелчке правой кнопкой мыши на
выделенной области окна Command
History
появляется
всплывающее меню. Выбор пункта Copy
приводит к копированию выделенной
последовательности в буфер обмена
Windows.
При щелчке правой кнопкой мыши на области
окна Command
Window
появляется всплывающее меню. Выбор
пункта Paste
приводит к вставке скопированной
последовательности команд в командную
строку. Весь вставленный в командную
строку набор команд отправляется на
выполнение нажатием клавиши <Enter>.
До
нажатия клавиши <Enter>
содержимое набора можно редактировать,
используя обычные приемы редактирования,
общие для Windows
– приложений, в том числе и с помощью
мыши. Можно вносить в команды необходимые
изменения, удалять лишние команды и
добавлять новые. При редактировании
клавиши <↑>
и
<↓>
могут использоваться для перемещения
между строками набора.
Третий
способ
– копирование из содержимого текстового
поля рабочего окна.
В
текстовом поле можно выделить с помощью
мыши любую команду и копировать ее в
буфер обмена операционной системы
Windows,
а затем вставить в командную строку.
Выделение и вставка производится теми
же средствами, что и в других Windows
– приложениях.
При
вычислениях любое арифметическое
выражение набирается с клавиатуры в
командной строке. Редактор MATLAB укажет
на синтаксические ошибки. Но он не
обнаружит так называемые семантические
ошибки,
когда, например, пользователь ошибочно
заменит знаки операций <+> на <–>
или неверной расстановкой скобок изменит
общий порядок выполнения операций и т.
д.
MATLAB
совместно с пакетом ToolBox
Symbolic
Math
(Глава 7) предоставляет возможность
визуального контроля введенного
выражения.
Пусть требуется
вычислить значение выражения
F=
при
x
= 0,1, y
= 0,2.
Введем
значения переменных x
и y.
Наберем с клавиатуры арифметическое
выражение F
и вычислим его значение, нажав клавишу
<Enter>.
Редактор MATLAB синтаксических ошибок
ввода не обнаружил. В результате получим
F
=
7,2111
(рис. 1.5).
В
третьей командной строке редактируется
предыдущая команда (<↑>)
для придания арифметическому выражению
F
статуса символьного с помощью команды
sym
(разд.
7.1). Выведенное в командное окно символьное
выражение F
синтаксически совпадает с арифметическим.
Рис. 1.5
Далее
команда pretty(F)
(см.
разд. 7.1) выводит в командное окно
символьное выражение F
в виде, близком к математической формуле.
Выведенная и исходная формулы не
совпадают. Предполагаемая ошибка ввода
– знаменатель исходной дроби не заключен
в скобки.
В
пятой командной строке редактируется
третья команда (<↑↑>)
для устранения ошибки ввода.
Затем
команда pretty(F)
отображает в командном окне исправленное
выражение. Теперь выведенная формула
совпадает с исходной.
В седьмой командной
строке редактируется пятая команда
(<↑↑>) для придания исправленному
символьному выражению статуса
арифметического. Седьмая команда
вычисляет правильный результат F =– 2,6904.
Иногда появляется
совершенно неожиданный или явно
неправильный результат. Так, если вы
попытаетесь вычислить приx
= -8, набирая
>> x=-8;r=x^(1/3)
r=
1.0000 + 1.7321i
ответ, который система
MATLABсоздает, не похож на
ожидаемый результат-2. Тем не менее,
полученный результат является кубическим
корнем из-8, что подтверждается
возведением этого результата в куб:
>> r^3
ans =
-8.0000 + 0.0000i
Дело в том, что
многозначная функция имеет в комплексной
плоскости три ветви, а уравнение x3
= -8– три разных значения корня:
>> solve(‘x^3=-8’)
ans =
[ -2]
[ 1-i*3^(1/2)]
[ 1+i*3^(1/2)]
Система MATLABвоспринимает для отрицательногоxкак значение
.
Поэтому для получения
ожидаемого результата при вычислении
, x = -8, надо набирать
>> x=-8;r=sign(x)*abs(x)^(1/3)
r=
-2
Это обстоятельство
надо обязательно учитывать, например,
при построении графика функции y
= .
Соседние файлы в папке OKMEC
- #
- #
Обзор
Неважно, как тщательно вы планируете и тестируете программы, которые вы написали, они не могут всегда запускаться так же гладко как ожидалось, когда выполняется при различных условиях. Это всегда – хорошая идея включать проверку ошибок в программы, чтобы гарантировать надежную операцию при всех условиях.
В MATLAB® программное обеспечение, можно решить, как программы отвечают на различные типы ошибок. Можно хотеть предложить пользователю более вход, отображение расширенная ошибка или предупреждение информации, или возможно повторить вычисление с помощью значений по умолчанию. Возможности обработки ошибок в MATLAB помогают вашей проверке программ на особое состояние ошибки и выполняют соответствующий код в зависимости от ситуации.
То, когда MATLAB обнаруживает серьезный отказ в команде или программе, это запускается, это собирает информацию о том, что происходило во время ошибки, отображает сообщение, чтобы помочь пользователю изучить то, что пошло не так, как надо и отключает команду или программу. Это называется throwing an exception. Можно получить исключение при вводе команд в командной строке MATLAB или при выполнении кода программы.
Получение исключения в командной строке
Если вы получаете исключение в подсказке MATLAB, у вас есть несколько опций о том, как иметь дело с нею аналогичный описанному ниже.
Определение отказа из сообщения об ошибке
Выполните сообщение об ошибке, которое отобразил MATLAB. Большинство сообщений об ошибке пытается объяснить, по крайней мере, мгновенную причину отказа программы. Часто существует достаточная информация, чтобы определить причину и что необходимо сделать, чтобы исправить ситуацию.
Рассмотрение провального кода
Если функция, в которой произошла ошибка, реализована как файл программы MATLAB, сообщение об ошибке должно включать линию, которая выглядит примерно так:
surf
Error using surf (line 49)
Not enough input arguments.
Текст включает имя функции, которое выдало ошибку (surf
, в этом случае), и показывает провальный номер строки в программном файле этой функции. Кликните по номеру строки; MATLAB открывает файл и располагает курсор в местоположении в файле где порожденная ошибка. Можно смочь определить причину ошибки путем исследования этой линии и кода, который предшествует ему.
Продвижение через код в отладчик
Можно использовать Отладчик MATLAB, чтобы продвинуться через провальный код. Кликните по подчеркнутому тексту ошибки, чтобы открыть файл в редакторе MATLAB в или около точки ошибки. Затем кликните по дефису в начале той линии, чтобы установить точку останова в том местоположении. Когда вы повторно выполняете свою программу, MATLAB приостанавливает выполнение в точке останова и позволяет вам продвинуться через код программы. Команда dbstop on error
также полезно в нахождении точки ошибки.
См. документацию относительно Отладки Файлы кода MATLAB для получения дополнительной информации.
Получение исключения в коде программы
Когда вы написали свою собственную программу в программном файле, вы можете исключения catch и попытка обработать или разрешить их вместо того, чтобы позволить вашей программе завершать работу. Когда вы отлавливаете исключение, вы прерываете нормальный процесс завершения и вводите блок кода, который справляется с дефектной ситуацией. Этот блок кода называется catch block.
Некоторые вещи, которые вы можете хотеть сделать в блоке выгоды:
-
Исследуйте информацию, которая была получена об ошибке.
-
Соберите дополнительную информацию, чтобы сообщить пользователю.
-
Попытайтесь выполнить задачу под рукой некоторым другим способом.
-
Очистите любые нежелательные побочные эффекты ошибки.
Когда вы достигаете конца блока выгоды, можно или продолжить выполнять программу, если это возможно, или отключать ее.
Используйте MException
возразите, чтобы получить доступ к информации об исключении в вашей программе. Для получения дополнительной информации смотрите, Отвечают на Исключение.
Генерация нового исключения
Когда ваш код программы обнаруживает условие, которое или заставит программу привести к сбою или привести к недопустимым результатам, это должно выдать исключение. Эта процедура
-
Сохраняет информацию о том, что пошло не так, как надо и что код выполнял во время ошибки.
-
Собирает любую другую уместную информацию об ошибке.
-
Дает MATLAB команду выдавать исключение.
Используйте MException
возразите, чтобы получить информацию об ошибке. Для получения дополнительной информации смотрите, Выдают Исключение.
In this Insight, I’ll go over 5 common MATLAB error messages, what they mean, and how to fix them. Hopefully, after reading this post you’ll find yourself being more productive, and maybe even help your friends with their code.
Most forums online where people post MATLAB questions generate quite a bit of duplicates, and PhysicsForums is no exception. The fact is, there are just certain situations that come up constantly in MATLAB, and if you’re a newer user, don’t consider yourself a programmer, or haven’t used the software in a while, then you’re likely to get tripped up and receive one of those red error messages. It can be especially frustrating when the message doesn’t make sense to you, or your best efforts to fix it come up dry.
Table of Contents
1
1. Error using * Inner matrix dimensions must agree.
By far the most common error message I see posted about by new users is this one. They create a few matrices or vectors and just go to multiply them with A*B, and this message is returned. Some example code that produces this message is:
A = [1 2 3]; B = [4 5 6]; A*B Error using * Inner matrix dimensions must agree.
The key to this error message is usually that people are not aware of the elementwise operators in MATLAB. The * operator performs matrix multiplication, where an NxM matrix is multiplied by an MxP matrix, resulting in an NxP matrix. Notice how those matrices have the common dimension “M”? That’s where this message comes from; it’s a common inner dimension.
Most often, you simply need to use .* instead of * to perform the elementwise multiplication, where corresponding elements are multiplied and the result is the same size as the inputs.
A.*B ans = 4 10 18
For more information about the different MATLAB operators, see Array vs. Matrix Operations. Note that even though this error message is the most common in this situation (since, well, multiplication is pretty popular) there are similar messages for the misuse of ^, /, and as opposed to .^, ./, and ..
2. Index exceeds matrix dimensions.
Quite simply, this error arises when you try to reference an element that doesn’t exist. For example, if the matrix has N elements, and you try to index into the N+1 element:
A = magic(5)
A =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
A(26)
Index exceeds matrix dimensions.
To fix this error, double-check that the matrix is the size you were expecting it to be and that the index you’re using is also what you expect. For example, if the index is the result of a calculation or is part of a loop, then you might need to adjust the calculation of the number of loop iterations. Some useful functions to check sizes and number of elements are numel(), size(), and length().
3. Subscript indices must either be real positive integers or logicals.
The most common reason this message arises is that people come to MATLAB from other programming languages and can’t get used to the fact that MATLAB indexing begins at 1. A(1) is the first element in a vector or matrix (or equivalently A(1,1)), not A(0) like in other programming languages!
A = magic(3)
A =
8 1 6
3 5 7
4 9 2
A(0)
Subscript indices must either be real positive integers or logicals.
There are a number of theories for why MATLAB uses 1-based indexing, but ultimately the answer is pretty simple. 1-based indexing is the language of Mathematics, as confirmed by Cleve Moler himself in a comment on this April Fools blog post.
We have always had BOTH 0-based indexing and 1-based indexing. In order to distinguish between the two, 0-based indices are followed by “+1″. The 1-based indices are preferred becaused they are the language of mathematics. — Cleve
I won’t expound on this anymore, but suffice it to say if you’re interested in this, a quick google search will turn up bountiful results, as it has a long and contentious history!
This error message can also arise if you use a noninteger (or negative) value to index. What is MATLAB supposed to do with A(1.5) or A(-3)? In this context, it’s again likely that you’ll want to check the bounds of any loop statements in your code to make sure they aren’t producing decimal or negative values for indexing.
4. The expression to the left of the equals sign is not a valid target for an assignment.
This error message arises because of misuse of the = and == operators. The = operator does an assignment, and the == operator does a logical test for equality. In the context of an if statement, for example, the if operator is expecting to see a logical condition to determine whether to continue executing code. So the following example code produces this error:
n = 5;
if n = 4
n = n.^2;
end
if n = 4
|
Error: The expression to the left of the equals sign is not a valid target for an assignment.
To fix this all you need to do is use == instead:
n = 5; if n == 4 n = n.^2; end
This code outlines the differences between the two operators more clearly:
A = 1:5 A = 1 2 3 4 5 B = 5; A == B ans = 0 0 0 0 1 C = A == B C = 0 0 0 0 1
In short: when you need to compare values, use ==. When you want to assign a value, use =.
5. Subscripted assignment dimension mismatch.
This error message arises because of an attempt to assign a vector or matrix into a compartment that it does not fit in. The dimension of the subscripted elements does not match the dimension of the assignment. For example, you cannot assign the first element in a matrix to be a vector, because there is only room for 1 element:
A = magic(3)
A =
8 1 6
3 5 7
4 9 2
A(1) = [4 5 6]
Subscripted assignment dimension mismatch.
This error can be much more subtle when you’re working with large matrices or loops, and it can occur because of a mismatch on either side of the equals sign. Sometimes the size of a vector or matrix can grow in an unexpected way in a loop, and you’ll receive this message and wonder what went wrong. The best way to debug this error is to double-check that all of your assignments are the sizes you expect them to be and that your matrices are growing (or not) as you expect them to.
If you don’t have any loops, just break the statement apart and check the size of each side. You won’t get this error if the sizes match exactly:
size(A(1:3)) ans = 1 3 size([4 5 6]) ans = 1 3 A(1:3) = [4 5 6] A = 4 1 6 5 5 7 6 9 2
Feedback
Obviously, I could go on with another 25 error messages, but I think these are the most common ones I see people posting about. If you’re interested in reading about some others, check out this link:
http://en.wikibooks.org/wiki/MATLAB_Programming/Error_Messages
Post about your favorite or least favorite MATLAB error messages in the comments, and let me know what you think!