Main Content

예외 발생시키기

프로그램이 예상대로 완료되지 못하게 하거나 잘못된 결과를 생성하는 오류를 감지할 경우에는, 예외를 발생시켜 더 이상 실행되는 것을 중지하고 오류를 보고해야 합니다. 기본적으로 수행할 단계는 다음과 같습니다.

  1. 오류를 감지합니다. 이는 종종 현재 연산의 출력값을 확인하는 if 문이나 try/catch 문과 같은 일부 유형의 조건문을 사용하여 수행합니다.

  2. 오류를 나타내는 MException 객체를 생성합니다. 생성자를 호출할 때 오류 ID와 오류 메시지를 이 객체에 추가합니다.

  3. 현재 오류를 야기했을 수도 있는 기타 예외가 있는 경우, 발생시키려는 단일 MExceptioncause 필드에 각 예외에 대한 MException 객체를 저장할 수 있습니다. 이렇게 하려면 addCause 함수를 사용하십시오.

  4. 현재 오류에 대해 제안할 수 있는 수정 사항이 있는 경우, 발생시키려는 MExceptionCorrection 필드에 수정 사항을 추가하면 됩니다. 이렇게 하려면 addCorrection 함수를 사용하십시오.

  5. throw 함수 또는 throwAsCaller 함수를 사용하여 MATLAB®에서 예외를 발생시키도록 합니다. 이때 MATLAB은 MExceptionstack 필드에 호출 스택 정보를 저장하고, 현재 실행 중인 함수를 종료한 다음, 키보드 또는 호출하는 함수의 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.