try, catch
명령문을 실행하여 결과 오류 포착
구문
trystatements
catchexception
statements
end
설명
try
는 statements
, catch statements
endtry
블록에서 명령문을 실행하고 catch
블록에서 결과 오류를 포착합니다. 이러한 접근 방식을 활용하면, 일련의 프로그램 명령문에 대한 디폴트 오류 동작을 재정의할 수 있습니다. try
블록의 명령문이 오류를 생성하면 프로그램 제어가 즉시 오류 처리 명령문이 포함되어 있는 catch
블록으로 넘어갑니다.
exception
은 오류를 식별할 수 있는 MException
객체입니다. catch
블록은 현재 예외 객체를 exception
의 변수에 할당합니다.
try
와 catch
블록은 모두 중첩 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
을 호출하면 그 자체로 오류가 발생합니다. try
와 catch
를 사용하면 이 코드는 예외를 포착하고 이를 경고로 다시 패키징하여 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
블록 사용을 허용하지 않습니다.
확장 기능
스레드 기반 환경
MATLAB®의 backgroundPool
을 사용해 백그라운드에서 코드를 실행하거나 Parallel Computing Toolbox™의 ThreadPool
을 사용해 코드 실행 속도를 높일 수 있습니다.
이 함수는 스레드 기반 환경을 완전히 지원합니다. 자세한 내용은 스레드 기반 환경에서 MATLAB 함수 실행하기 항목을 참조하십시오.
버전 내역
R2006a 이전에 개발됨R2022a: 명령문이 오류 없이 실행될 때의 성능이 개선됨
try
블록 내 명령문이 오류 없이 실행될 경우 향상된 성능을 보입니다. 예를 들어, 다음 코드는 이전 릴리스보다 약 6배 빠릅니다.
function testTryPerformance x = 1; for i = 1:1e8 try x = x * i; catch warning("Assignment was not successful.") x = 1; end end end
대략적인 실행 시간은 다음과 같습니다.
R2021b: 2.3초
R2022a: 0.4초
코드 실행 시간은 Windows® 10, Intel® Xeon® CPU E5-1650 v4 @ 3.60GHz 테스트 시스템에서 timeit
함수를 사용하여 측정했습니다.
timeit(@testTryPerformance)
MATLAB 명령
다음 MATLAB 명령에 해당하는 링크를 클릭했습니다.
명령을 실행하려면 MATLAB 명령 창에 입력하십시오. 웹 브라우저는 MATLAB 명령을 지원하지 않습니다.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)