================================ Outline ====================================
예외처리
- try/throw/catch 구문
----------------------------------------------------------------------------
try/throw/catch 구문
try: 수행하고자 하는 코드를 넣는다.
throw: 제어문을 넣어서 특정 조건에 해당되는 경우 throw를 사용하여 값 던진다.
catch: throw에서 받은 값을 사용자가 원하는 형(type)으로 받는다.
try-throw-catch문은 흐름문의 일종으로써 프로그램의 흐름을 알아볼 때 사용된다.
기본 문법은 다음과 같다.
try
{
if (예외 조건)
throw 예외 객체;
}
catch (예외 객체)
{
예외 처리
}
** try블록과 catch는 사이에는 다른 코드가 들어가서는 안된다.

/*** try catch 구문 ***/ #include <iostream>
using namespace std;
void divide(int A, int B) { if(0 == B) { throw B; // B가 0일 경우 B를 catch로 던진다. throw가 실행되면 해당 함수는 종료된다. } else if(0 == A) { throw A; // A가 0일 경우 A를 catch로 던진다. } cout<<"몫은" << A/B <<"입니다.\n"; cout<<"나머지는" << A%B <<"입니다.\n"; }
int main(void) { int A, B; cout<< "나누고 싶은 숫자를 입력하세요" << endl; cin >> A ; cout<<"나눌 싶은 숫자를 입력하세요"<<endl; cin >> B;
try { divide(A, B); cout << "======================================================\n"; } catch(int iTest) //throw에서 받은 값을 int iTest에 넣는다. { cout << iTest << "로는 나눌 수 없습니다." <<endl; }
return 0; }
|
throw가 실행되면 해당 함수는 종료됨으로 return과 같은 역할을 하지만 다른 점이 있다면 throw문은 반환 값이 항상 존재한다는 것이다.
cout으로 표현한 ‘================’ 값이 try -catch 문의 작동여부에 따라 출력이 되는 것을 알 수 있다.
** exit 함수는 현재 열려 있는 파일들을 종료하고 닫도록 해주는 함수이다. 즉 잘 정돈 후 프로그램을 종료하도록 해주는 함수이다.
** catch문도 오버로딩이 가능함으로 throw의 값에 따라 실행하는 catch문을 따로 작성할 수 있다.
교재 p/407, 스택 되감기
#include <iostream> #include <stdio.h> using namespace std;
class C { int a;
public: C() { puts("Creator called"); } ~C() { puts("Destructor called"); } };
void divide(int a, int d) { if(d==0) throw "0으로는 나눌 수 없습니다."; cout<<"나누기 결과 ="<<a/d<<"입니다.\n"; }
void calc(int t, const char *m) { C c; divide(10,0); }
int main(void) { try { calc(1, "계산"); } catch(const char * message) { puts(message); } puts("프로그램이 종료됩니다.");
return 0; }
|

try - catch문을 중첩으로 사용하는 것도 가능하다.
교재 p/409, 중첩 try- catch문

#include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> using namespace std;
int main(void) { int Num; int Age; char cBin; char Name[30];
try { printf("학번을 입력하시오 : "); scanf("%d", &Num); if('\n'==(cBin=getchar())) ; if(Num <= 0) throw Num; try { printf("이름을 입력하시오 : "); gets(Name); if(strlen(Name) < 4) throw "이름이 너무 짧습니다."; printf("나이를 입력하시오 : "); scanf("%d", &Age); if(Age <= 0) throw Age; printf("입력한 정보 => 학번:%d, 이름:%s, 나이:%d\n", Num, Name, Age); } catch(const char *Message) { puts(Message); } catch(int) { throw; } } catch(int n) { printf("%d는 음수이므로 적합하지 않습니다.\n", n); }
return 0; }
|
catch 블록에서 예외를 다시 던질 때는 예외 객체를 지정할 필요 없이 throw 명령만 단독으로 사용한다. 받은 객체를 그대로 다시 넘기는 것이므로 예외 객체를 명시할 필요가 없으며 직접 처리하지 않으므로 catch의 괄호 안에 예외 객체의 이름을 줄 필요도 없다.