throw
引发异常
说明
throw(
根据 exception
)MException
对象 exception
中包含的信息引发异常。该异常终止当前正在运行的函数,并将控制权返回到键盘或封闭的 catch
块。从 try/catch
语句外部引发异常时,MATLAB® 将错误消息显示在命令行窗口中。
throw
函数不同于 throwAsCaller
和 rethrow
函数,它从 MATLAB 调用函数的位置创建堆栈跟踪。
可以通过 try/catch
语句或 MException.last
函数访问 MException
对象。
示例
创建并引发 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
对象。
比较 throw
和 rethrow
的行为
在您的工作文件夹中创建一个函数 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 行。
输入参数
exception
— 包含错误的原因和位置的异常
MException
对象
包含错误的原因和位置的异常,指定为标量 MException
对象。
扩展功能
基于线程的环境
使用 MATLAB® backgroundPool
在后台运行代码或使用 Parallel Computing Toolbox™ ThreadPool
加快代码运行速度。
版本历史记录
在 R2007b 中推出
另请参阅
rethrow
| throwAsCaller
| MException.last
| try,
catch
| error
MATLAB 命令
您点击的链接对应于以下 MATLAB 命令:
请在 MATLAB 命令行窗口中直接输入以执行命令。Web 浏览器不支持 MATLAB 命令。
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)