Main Content

try, catch

명령문을 실행하여 결과 오류 포착

구문

try
   statements
catch exception
   statements
end

설명

예제

try statements, catch statements endtry 블록에서 명령문을 실행하고 catch 블록에서 결과 오류를 포착합니다. 이러한 접근 방식을 활용하면, 일련의 프로그램 명령문에 대한 디폴트 오류 동작을 재정의할 수 있습니다. try 블록의 명령문이 오류를 생성하면 프로그램 제어가 즉시 오류 처리 명령문이 포함되어 있는 catch 블록으로 넘어갑니다.

exception은 오류를 식별할 수 있는 MException 객체입니다. catch 블록은 현재 예외 객체를 exception의 변수에 할당합니다.

trycatch 블록은 모두 중첩 try/catch 문을 포함할 수 있습니다.

예제

모두 축소

세로로 결합할 수 없는 두 개의 행렬을 만듭니다.

A = rand(3);
B = ones(5);

C = [A; B];
Error using vertcat
Dimensions of matrices being concatenated are not consistent.

try/catch를 사용하여 차원에 대한 정보가 더 자세히 표시되도록 합니다.

try
   C = [A; B];
catch ME
   if (strcmp(ME.identifier,'MATLAB:catenate:dimensionMismatch'))
      msg = ['Dimension mismatch occurred: First argument has ', ...
            num2str(size(A,2)),' columns while second has ', ...
            num2str(size(B,2)),' columns.'];
        causeException = MException('MATLAB:myCode:dimensions',msg);
        ME = addCause(ME,causeException);
   end
   rethrow(ME)
end 
Error using vertcat
Dimensions of matrices being concatenated are not consistent.

Caused by:
    Dimension mismatch occurred: First argument has 3 columns while second has 5 columns.

행렬의 차원이 일치하지 않으면 MATLAB®이 불일치에 대해 더 자세한 정보를 표시합니다. 그 외 모든 오류는 원래 메시지로 표시됩니다.

존재하지 않는 함수 notaFunction을 호출하여 생성된 예외를 포착합니다. 예외가 있으면 경고를 발생시키고 출력값에 값 0을 할당합니다.

try
    a = notaFunction(5,6);
catch
    warning('Problem using function.  Assigning a value of 0.');
    a = 0;
end
Warning: Problem using function.  Assigning a value of 0.

notaFunction을 호출하면 그 자체로 오류가 발생합니다. trycatch를 사용하면 이 코드는 예외를 포착하고 이를 경고로 다시 패키징하여 MATLAB이 다음 명령을 계속 실행할 수 있게 해 줍니다.

try/catch를 사용하여 여러 오류 유형을 다르게 처리할 수 있습니다.

  • 함수 notaFunction이 정의되어 있지 않으면 오류 대신 경고를 발생시키고 출력값에 값 NaN을 할당합니다.

  • notaFunction.m이 있지만 함수 대신 스크립트로 존재하면 오류 대신 경고를 발생하고 스크립트를 실행하며 출력값에 값 0을 할당합니다.

  • MATLAB이 다른 이유로 오류를 발생시키는 경우 예외를 다시 발생시킵니다.

try
    a = notaFunction(5,6);
catch ME
    switch ME.identifier
        case 'MATLAB:UndefinedFunction'
            warning('Function is undefined.  Assigning a value of NaN.');
            a = NaN;
        case 'MATLAB:scriptNotAFunction'
            warning(['Attempting to execute script as function. '...
                'Running script and assigning output a value of 0.']);
            notaFunction;
            a = 0;
        otherwise
            rethrow(ME)
    end
end
Warning: Function is undefined.  Assigning a value of NaN. 

  • try 블록 내에서 여러 개의 catch 블록을 사용할 수 없지만 완전한 try/catch 블록을 중첩할 수는 있습니다.

  • 일부 다른 언어들과 달리 MATLAB은 try/catch 문 내에서 finally 블록 사용을 허용하지 않습니다.

확장 기능

버전 내역

R2006a 이전에 개발됨

모두 확장