nakka soft world !

예외 (Exception) 본문

프로그래밍언어/C++

예외 (Exception)

nakka 2017. 3. 27. 19:33
728x90

예외 (Exception)



1. C스타일 예외 처리.

int foo()

{

if(1)

return 0;   // 실패... 진짜?

return 1;

}


int main()

{

int ret = foo();

}



2. C++스타일 예외 처리

int foo()

{

if(1)   // 실패

throw 1;

throw 3.4;

throw "aaa";


return 1;

}


int main()

{

try

{

int ret = foo();

}

catch (int a)

{

cout << "int 예외 처리" << endl;

}

catch (double a)

{

cout << "double 예외 처리" << endl;

}

catch (...)

{

cout << "... 예외 처리" << endl;

}

}



3. 예외 전용 클래스

class MemoryException

{

};


int foo()

{

if(1)   // 실패

throw MemoryException();


return 1;

}


int main()

{

try

{

int ret = foo();

}

catch (MemoryException& m)

{

cout << "int 예외 처리" << endl;

}

}



4. new와 예외


int main()

{

int* p = new int[100];


if(p == 0)

{



}

delete[] p;

}


int main()

{

try

{

int* p = new int[100];


// 메모리 사용

delete[] p;

}

catch (std::bad_alloc& e)

{


}

}



5. 예외의 표시


// C++98/03

void foo() throw() // 예외가 없다.

void foo() // 예외가 있을수도 있고, 없을 수도 있다.

void foo() throw(MemoryException) // 

{

}

// C++11

void foo() noexcept // 예외가 없다. - 꼭써야 하는건 아니지만 Compiler최적화에 도움이 됨. 써주는게 좋음.

void foo() // 예외가 있을수도 있고, 없을 수도 있다.

{

}

int main()

{

foo();

}



728x90
Comments