Main Content

このページの翻訳は最新ではありません。ここをクリックして、英語の最新版を参照してください。

例外のスロー

プログラムに予想通りの終了を阻止するエラー、あるいは間違った結果をもたらすエラーが検出された場合は、実行を停止させ、例外をスローしてエラーを報告します。基本的なステップは次のとおりです。

  1. エラーを検出します。これは、多くの場合、現在の操作の出力をチェックするifまたはtry/catchステートメントなど、あるタイプの条件付きステートメントで行われます。

  2. エラーを表すMExceptionオブジェクトを作成します。コンストラクターを呼び出す際に、エラー識別子とエラー メッセージをオブジェクトに追加します。

  3. 現在のエラーの原因となっている可能性のある他の例外がある場合は、スローしようとしている 1 つのMExceptioncauseフィールドのそれぞれにMExceptionオブジェクトを保存できます。このために、関数addCauseを使用します。

  4. 現在のエラーに対して推奨可能な修正がある場合、それをスローしようとしているMExceptionCorrectionフィールドに追加できます。このために、関数addCorrectionを使用します。

  5. 関数throwまたはthrowAsCallerを使用して、MATLAB®で例外をスローするようにします。この時点で、MATLAB によってMException堆栈フィールドに呼び出しスタックの情報が格納され、現在実行中の関数が終了され、キーボードまたは呼び出し側関数内の現在の catch ブロックにコントロールが返されます。

例外のスロー方法に関する推奨

この例では、説明したばかりの手順で例外をスローする方法を説明します。

特定のインデックスを使用して特定の配列にインデックス付けする関数indexIntoArrayを作成します。関数は MATLAB がスローしたエラーをキャッチし、エラーに関する一般的な情報を提供する例外を作成します。エラーをキャッチすると、入力数または特定のインデックスがエラーに含まれているかどうかを検出します。含まれている場合、関数は失敗の原因に関するより詳細な情報を含む追加の例外を追加し、可能であれば修正を推奨します。

functionindexIntoArray(A,idx)% 1) Detect the error.tryA(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.ifnargin < 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);endthrow(baseException);endtryassert(isnumeric(idx),“MYFUN:notNumeric',...'Indexing array is not numeric.')catchcauseException baseException = addCause(baseException,causeException);endifany(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)endend

インデックスを指定せずに関数を呼び出す場合、関数は詳細なエラーをスローし、修正を推奨します。

A = [13 42; 7 20]; indexIntoArray(A)
Error using indexIntoArray (line 21) 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 (line 41) Unable to index into array. Caused by: Error using indexIntoArray (line 25) Indexing array is not numeric. Indexing array is too large.