目录
error函数的功能是抛出错误并显示消息。
- error(msg)
- error(msg,A1,...,An)
- error(errID,___)
- error(errorStruct)
- error(correction,___)
error(msg) 抛出错误并显示错误消息。
error(msg,A1,...,An) 显示一条错误消息,其中包含格式设置转换字符,例如随 MATLAB® sprintf 函数一起使用的字符。msg 中的每个转换字符都会转换为 A1,...,An 中的一个值。
error(errID,___) 包含此异常中的错误标识符。此标识符可用于区分错误,它还允许您控制在 MATLAB 遇到错误时系统做何反应。可以包括先前语法中的任何输入参数。
error(errorStruct) 使用标量结构体中的字段抛出错误。
error(correction,___) 为异常提供建议修复。可以包括先前语法中的任何输入参数。
- msg = 'Error occurred.';
- error(msg)
- Error occurred.
抛出带有换行符的格式化错误消息。如果希望 MATLAB 转换错误消息中的特殊字符(例如 \n),必须为 error 指定多个输入参数。在错误消息中包含有关变量 n 的类的信息。
- n = 7;
- if ~ischar(n)
- error('Error. \nInput must be a char, not a %s.',class(n))
- end
- Error.
- Input must be a char, not a double.
如果对 error 只使用一个输入参数,则 MATLAB 不会将 \n 转换为换行符。
- if ~ischar(n)
- error('Error. \nInput must be a char.')
- end
- Error. \nInput must be a char.
抛出带有标识符的错误。
- if ~ischar(n)
- error('MyComponent:incorrectType',...
- 'Error. \nInput must be a char, not a %s.',class(n))
- end
- Error.
- Input must be a char, not a double.
使用 MException.last 查看最后未捕获的异常。
- exception = MException.last
- exception =
-
- MException with properties:
-
- identifier: 'MyComponent:incorrectType'
- message: 'Error.
- Input must be a char, not a double.'
- cause: {0x1 cell}
- stack: [0x1 struct]
创建包含消息和标识符字段的结构体。为确保示例简洁,不要使用堆栈字段。
- errorStruct.message = 'Data file not found.';
- errorStruct.identifier = 'MyFunction:fileNotFound';
- errorStruct =
-
- message: 'Data file not found.'
- identifier: 'MyFunction:fileNotFound'
抛出错误。
- error(errorStruct)
- Data file not found.
创建需要一个输入参数的函数 hello。在错误消息中添加建议的输入参数 "world"。
- function hello(audience)
- if nargin < 1
- aac = matlab.lang.correction.AppendArgumentsCorrection('"world"');
- error(aac, 'MATLAB:notEnoughInputs', 'Not enough input arguments.')
- end
- fprintf("Hello, %s!\n", audience)
- end
不带参数调用函数。
- hello
- Error using hello (line 4)
- Not enough input arguments.
- Did you mean:
- >> hello("world")
有关错误的信息,指定为字符向量或字符串标量。该消息显示为错误消息。要设置消息格式,请使用转义序列,例如 \t 或 \n。还可以使用 sprintf 函数支持的任何格式设定符,例如 %s 或 %d。通过 A1,...,An 输入参数指定转换设定符的值。有关详细信息,可以参考格式化文本。
注意:如果希望 MATLAB 转换错误消息中的特殊字符(例如 \t、\n、%s 和 %d),必须为 error 指定多个输入参数。
错误标识符,指定为字符向量或字符串标量。使用错误标识符有助于确定错误来源或控制选定的部分程序错误。
错误标识符包括一个或多个组件字段和一个助记键字段。各字段必须用冒号分隔。例如,具有组件字段 component 和助记键字段 mnemonic 的错误标识符指定为 'component:mnemonic'。组件字段和助记键字段都必须以字母开头。其余字符可以是字母数字字符(A–Z、a–z、0–9)和下划线。空白字符不能出现在 errID 中的任何位置。参考MException。
| message | 错误消息。有关详细信息,可参考msg。 |
| identifier | 错误标识符。有关详细信息,可参考errID。 |
| stack | 错误的堆栈字段。如果 errorStruct 包含 stack 字段,则 error 使用它设置该错误的堆栈字段。指定 stack 时,在堆栈帧中使用绝对文件名和嵌套函数的整个函数序列。此字符向量与 dbstack('-completenames') 返回的字符向量相同。 |
提示
抛出错误时,MATLAB 会捕获该错误的相关信息并将其存储在 MException 类对象数据结构体中。可以使用 try/catch 来访问异常对象中的信息。或者,如果程序由于异常而终止,并将控制权返回至命令提示符,则可以使用 MException.last。
如果 try 内发生错误,MATLAB 不会停止执行程序。在本例中,MATLAB 将控件传递到 catch 块中。
如果 error 的所有输入为空,则 MATLAB 不会抛出错误。