例外のスロー
プログラムに予想通りの終了を阻止するエラー、あるいは間違った結果をもたらすエラーが検出された場合は、実行を停止させ、例外をスローしてエラーを報告します。基本的なステップは次のとおりです。
エラーを検出します。これは、多くの場合、現在の操作の出力をチェックする
if
またはtry/catch
ステートメントなど、あるタイプの条件付きステートメントで行われます。エラーを表す
MException
オブジェクトを作成します。コンストラクターを呼び出す際に、エラー識別子とエラー メッセージをオブジェクトに追加します。現在のエラーの原因となっている可能性のある他の例外がある場合は、スローしようとしている 1 つの
MException
のcause
フィールドのそれぞれにMException
オブジェクトを保存できます。このために、関数addCause
を使用します。現在のエラーに対して推奨可能な修正がある場合、それをスローしようとしている
MException
のCorrection
フィールドに追加できます。このために、関数addCorrection
を使用します。関数
throw
またはthrowAsCaller
を使用して、MATLAB® で例外をスローするようにします。この時点で、MATLAB によってMException
のstack
フィールドに呼び出しスタックの情報が格納され、現在実行中の関数が終了され、キーボードまたは呼び出し側関数内の現在の catch ブロックにコントロールが返されます。
例外のスロー方法に関する推奨
この例では、説明したばかりの手順で例外をスローする方法を説明します。
特定のインデックスを使用して特定の配列にインデックス付けする関数 indexIntoArray
を作成します。関数は MATLAB がスローしたエラーをキャッチし、エラーに関する一般的な情報を提供する例外を作成します。エラーをキャッチすると、入力数または特定のインデックスがエラーに含まれているかどうかを検出します。含まれている場合、関数は失敗の原因に関するより詳細な情報を含む追加の例外を追加し、可能であれば修正を推奨します。
function indexIntoArray(A,idx) % 1) Detect the error. try A(idx) catch % 2) Construct an MException object to represent the error. errID = 'MYFUN:BadIndex'; msg = 'Unable to index into array.'; baseException = MException(errID,msg); % 3) Store any information contributing to the error. if nargin < 2 causeException = MException('MATLAB:notEnoughInputs','Not enough input arguments.'); baseException = addCause(baseException,causeException); % 4) Suggest a correction, if possible. if(nargin > 1) exceptionCorrection = matlab.lang.correction.AppendArgumentsCorrection('1'); baseException = baseException.addCorrection(exceptionCorrection); end throw(baseException); end try assert(isnumeric(idx),'MYFUN:notNumeric', ... 'Indexing array is not numeric.') catch causeException baseException = addCause(baseException,causeException); end if any(size(idx) > size(A)) errID = 'MYFUN:incorrectSize'; msg = 'Indexing array is too large.'; causeException2 = MException(errID,msg); baseException = addCause(baseException,causeException2); end % 5) Throw the exception to stop execution and display an error % message. throw(baseException) end end
インデックスを指定せずに関数を呼び出す場合、関数は詳細なエラーをスローし、修正を推奨します。
A = [13 42; 7 20]; indexIntoArray(A)
Error using indexIntoArray
Unable to index into array.
Caused by:
Not enough input arguments.
Did you mean:
>> indexIntoArray(A, 1)
大きすぎる非数値インデックス配列を指定して関数を呼び出す場合、関数は詳細なエラーをスローします。
A = [13 42; 7 20]; idx = ['a' 'b' 'c']; indexIntoArray(A, idx)
Error using indexIntoArray
Unable to index into array.
Caused by:
Error using assert
Indexing array is not numeric.
Indexing array is too large.