본문 바로가기

C/C++

C에서 Try-Catch 사용하기

C에서 Try-Catch 사용하기


이런게 되나... 싶었는데 된다

http://stackoverflow.com/questions/385975/error-handling-in-c-code 참조



개념


setjmp를 활용한 것이다. 평소에 대체 setjmp는 뭐에 써먹나 했는데 이렇게 활용 가능할 줄이야... 놀랍다

#include <setjmp.h>
#include <stdio.h>

jmp_buf x;

void f()
{
longjmp(x,5); // throw 5;
}

int main()
{
// output of this program is 5.

int i = 0;

if ( (i = setjmp(x)) == 0 )// try{
{
f();
} // } --> end of try{
else // catch(i){
{
switch( i )
{
case 1:
case 2:
default: fprintf( stdout, "error code = %d\n", i); break;
}
} // } --> end of catch(i){
return 0;
}





실전 활용


매크로를 사용해 각 심볼인 TRY, CATCH, ETRY(End of TRY)를 정의하고, 아래와 같이 만들면 된다

#include <stdio.h>
#include <setjmp.h>

#define TRY do{ jmp_buf ex_buf__; if( !setjmp(ex_buf__) ){
#define CATCH } else {
#define ETRY } }while(0)
#define THROW longjmp(ex_buf__, 1)

int main(int argc, char **argv) {
TRY
{
printf("In Try Statement\n");
THROW;
printf("I do not appear\n");
}
CATCH
{
printf("Got Exception!\n");
}
ETRY;

return 0;
}




'C/C++' 카테고리의 다른 글

Ubuntu C Include Paths  (0) 2016.08.08
errno 의미  (0) 2015.12.13
C++ Casting  (0) 2015.10.17
개미수열  (0) 2015.03.04
C++11 Stringtokenizer  (0) 2015.01.26