Main Content

throw

引发异常

说明

示例

throw(exception) 根据 MException 对象 exception 中包含的信息引发异常。该异常终止当前正在运行的函数,并将控制权返回到键盘或封闭的 catch 块。从 try/catch 语句外部引发异常时,MATLAB® 将错误消息显示在命令行窗口中。

throw 函数不同于 throwAsCallerrethrow 函数,它从 MATLAB 调用函数的位置创建堆栈跟踪。

可以通过 try/catch 语句或 MException.last 函数访问 MException 对象。

示例

全部折叠

如果工作区中没有输入变量名称,则会引发异常。

str = input('Type a variable name: ','s');
if ~exist(str,'var')
    ME = MException('MyComponent:noSuchVariable', ...
        'Variable %s not found',str);
    throw(ME)
end

在命令提示符处,输入工作区中不存在的任何变量。例如,输入 notaVariable

Variable notaVariable not found

由于 notVariable 不在您的工作区中,MATLAB 会创建并抛出一个 MException 对象。

在您的工作文件夹中创建一个函数 combineArrays

function C = combineArrays(A,B)
try
    C = catAlongDim1(A,B);       % Line 3
catch exception
    throw(exception)             % Line 5
end
end

function V = catAlongDim1(V1,V2)
V = cat(1,V1,V2);                % Line 10
end

调用数组大小不同的 combineArrays 函数。

A = 1:5;
B = 1:4;

combineArrays(A,B)
Error using combineArrays
Dimensions of matrices being concatenated are not consistent.

堆栈指向 MATLAB 引发异常的第 5 行。

combineArrays 的第 5 行将 throw(exception) 替换为 rethrow(exception),并重新调用该函数。

combineArrays(A,B)
Error using cat
Dimensions of matrices being concatenated are not consistent.

Error in combineArrays>catAlongDim1
V = cat(1,V1,V2);       

Error in combineArrays
    C = catAlongDim1(A,B);      

rethrow 函数保留原始堆栈并指示错误位于第 3 行。

输入参数

全部折叠

包含错误的原因和位置的异常,指定为标量 MException 对象。

扩展功能

基于线程的环境
使用 MATLAB® backgroundPool 在后台运行代码或使用 Parallel Computing Toolbox™ ThreadPool 加快代码运行速度。

版本历史记录

在 R2007b 中推出