Main Content

rethrow

前回キャッチされた例外を再度スローする

説明

rethrow(exception) は、前回キャッチされた例外 exception を再度スローします。MATLAB® は通常、現在実行しているプログラムを終了してエラーに応答します。ただし、try/catch ブロックを使用して例外をキャッチします。これがプログラムの終了に割り込むため、独自のエラー処理手順を実行できます。プログラムを終了して例外を再度表示するには、rethrow ステートメントで catch ブロックを終了します。

rethrowerrorassert および throw のスタック トレースの処理は異なります。rethrow は、MATLAB が関数を実行したところからスタックを作成するのではなく、元の例外情報を維持して元のエラー ソースを再度追跡できるようにします。

すべて折りたたむ

入力を指定せずに surf を呼び出すことで MATLAB にエラーをスローさせます。例外をキャッチしてエラー識別子を表示し、例外を再スローします。

try
    surf
catch ME
    disp(['ID: ' ME.identifier])
    rethrow(ME)
end
ID: MATLAB:narginchk:notEnoughInputs
Error using surf (line 49)
Not enough input arguments.

作業フォルダーで、関数 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 オブジェクトとして指定します。

バージョン履歴

R2007b で導入