Main Content

throw

설명

예제

throw(exception)MException 객체인 exception에 포함된 정보를 기반으로 예외를 발생시킵니다. 예외는 현재 실행 중인 함수를 종료하고 키보드 또는 catch 블록으로 컨트롤을 반환합니다. try/catch 문 밖에서 예외를 발생시킬 경우 MATLAB®은 명령 창에 오류 메시지를 표시합니다.

throw 함수는 throwAsCallerrethrow 함수와 달리 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에 개발됨