Main Content

throw

説明

throw(exception) は、MException オブジェクト exception に含まれている情報に基づいて例外をスローします。例外により現在実行している関数は終了して、制御をキーボードまたは囲んでいる catch ブロックに返します。try/catch ステートメントの外部から例外をスローする場合、MATLAB® はコマンド ウィンドウにエラー メッセージを表示します。

関数 throwAsCaller と関数 rethrow とは異なり、関数 throw は、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 で導入