SlideShare a Scribd company logo
C++ Programming - 13th Study
C++ Programming - 13th Study
3
4
던지면(throw)
받아서(catch)
익셉션(exception)
C++ Programming - 13th Study
6
try {
// 익셉션이 발생할 코드
} catch (exception-type1 exception-name) {
// type1 익셉션을 받아서 처리할 코드
} catch (exception-type2 exception-name) {
// type2 익셉션을 받아서 처리할 코드
}
// 나머지 코드
7
8
int Divide(int num, int den)
{
return num / den;
}
int main() {
cout << Divide(5, 2) << endl;
cout << Divide(10, 0) << endl;
cout << Divide(3, 3) << endl;
}
int Divide(int num, int den)
{
if (den == 0)
throw invalid_argument("Divide by zero");
return num / den;
}
int main() {
try {
cout << Divide(5, 2) << endl;
cout << Divide(10, 0) << endl;
cout << Divide(3, 3) << endl;
} catch (const invalid_argument& e) {
cout << "Caught exception: " << e.what() << endl;
}
}
9
10
void readFile(const string& fileName,
vector<int>& dest)
{
ifstream istr;
int temp;
istr.open(fileName.c_str());
// 값을 하나씩 읽어서 vector에 저장
while (istr >> temp)
dest.push_back(temp);
}
int main()
{
vector<int> myInts;
const string fileName = "numbers.txt";
readFile(fileName, myInts);
for (size_t i = 0; i < myInts.size(); i++)
cout << myInts[i] << " ";
cout << endl;
}
11
void readFile(const string& fileName,
vector<int>& dest)
{
ifstream istr;
int temp;
istr.open(fileName.c_str());
if (istr.fail())
throw exception();
// 값을 하나씩 읽어서 vector에 저장
while (istr >> temp)
dest.push_back(temp);
}
int main()
{
vector<int> myInts;
const string fileName = "numbers.txt";
try {
readFile(fileName, myInts);
} catch (const exception& e) {
cerr << "Unable to open file "
<< fileName << endl;
return 1;
}
for (size_t i = 0; i < myInts.size(); i++)
cout << myInts[i] << " ";
cout << endl;
}
12
int Divide(int num, int den)
{
if (den == 0)
throw "Divide by zero";
return num / den;
}
int main() {
try {
cout << Divide(5, 2) << endl;
cout << Divide(10, 0) << endl;
cout << Divide(3, 3) << endl;
} catch (const string& s) {
cout << s.c_str() << endl;
}
}
익셉션으로 던질 데이터의 타입이 변경되면
catch 구문도 수정해야 함
13
void readFile(const string& fileName, vector<int>& dest) {
ifstream istr;
int temp;
istr.open(fileName.c_str());
if (istr.fail())
// 파일 열기 실패에 따른 익셉션
throw invalid_argument("");
// 값을 하나씩 읽어서 vector에 저장
while (istr >> temp)
dest.push_back(temp);
if (istr.eof())
istr.close();
else {
// 알 수 없는 오류에 의한 익셉션
istr.close();
throw runtime_error("");
}
}
try
{
readFile(fileName, myInts);
}
catch (const invalid_argument& e)
{
cerr << "Unable to open file " << fileName << endl;
return 1;
}
catch (const runtime_error& e)
{
cerr << "Error reading file " << fileName << endl;
return 1;
}
14
void readFile(const string& fileName, vector<int>& dest)
throw (invalid_argument, runtime_error) { … }
void readFile(const string& fileName, vector<int>& dest)
throw (invalid_argument, runtime_error);
void readFile(const string& fileName, vector<int>& dest) throw(); // C++98
void readFile(const string& fileName, vector<int>& dest) noexcept; // C++11
C++ Programming - 13th Study
16
 bad_alloc
 bad_cast
 bad_typeid
 bad_exception
 logic_error
 out_of_range, invalid_argument, length_error
 runtime_error
 range_error, overflow_error, underflow_error
17
C++ Programming - 13th Study
19
20
void f1() { throw 0; }
void f2() { f1(); }
void f3() { f2(); }
void f4() { f3(); }
int main()
{
try
{
f4();
}
catch (int e)
{
cout << e << endl;
}
}
함수 호출
스택 풀기
21
void funcOne() throw(exception) {
string str1;
string* str2 = new string();
funcTwo();
delete str2;
}
void funcTwo() throw(exception) {
ifstream istr;
istr.open("fileName");
throw exception();
istr.close();
}
int main()
{
try
{
funcOne();
}
catch (const exception& e)
{
cerr << "Exception caught!" << endl;
return 1;
}
}
예외 발생
실행 X → 지역 변수는 소멸자 실행
실행 X → 포인터 변수는 메모리 릭 발생
http://en.cppreference.com/w/cpp/memory/shared_ptr
http://en.cppreference.com/w/cpp/memory/unique_ptr
22
#include <memory>
void funcOne() throw(exception)
{
string str1;
// string* str2 = new string();
unique_ptr<string> str2(new string("Hello"));
funcTwo();
// delete str2;
}
23
void funcOne() throw(exception)
{
string str1;
string* str2 = new string();
try {
funcTwo();
} catch (...) {
delete str2;
throw; // 익셉션 재전송
}
delete str2;
}
“...”은 모든 타입의 익셉션을 매칭할 수 있음

More Related Content

What's hot (19)

PDF
Responsive Webdesign
nikflip
 
PDF
Juan
17gilmar
 
ODP
C++14 reflections
corehard_by
 
PPTX
Java лаб13
Enkhee99
 
PDF
Tester son JS, c'est possible !
goldoraf
 
PDF
ใบงานที่ 2 นาฬิกา
Kunagon Suwan
 
PDF
Java Thread Cronometro
jubacalo
 
PPTX
Александра Калинина "Trojan War: SinonJS"
Fwdays
 
PDF
Testování prakticky
Filip Procházka
 
PDF
Фатальный недостаток Node.js
Oleksii Okhrymenko
 
PDF
JavaScript Virus Code Example
Mohd Sohaib
 
DOCX
Caculadora pacho (1)
san jaramillo
 
PDF
Node.JS
eibaan
 
PDF
Papel progresistas
javier Soto
 
PPTX
Java осень 2012 лекция 6
Technopark
 
PDF
JavaScript в enterprise приложениях
MoscowJS
 
PDF
商派信息安全解决方案
wanglei999
 
PDF
Pjudicial-Dfortunato
sofialucia
 
PDF
Java AWT Calculadora
jubacalo
 
Responsive Webdesign
nikflip
 
Juan
17gilmar
 
C++14 reflections
corehard_by
 
Java лаб13
Enkhee99
 
Tester son JS, c'est possible !
goldoraf
 
ใบงานที่ 2 นาฬิกา
Kunagon Suwan
 
Java Thread Cronometro
jubacalo
 
Александра Калинина "Trojan War: SinonJS"
Fwdays
 
Testování prakticky
Filip Procházka
 
Фатальный недостаток Node.js
Oleksii Okhrymenko
 
JavaScript Virus Code Example
Mohd Sohaib
 
Caculadora pacho (1)
san jaramillo
 
Node.JS
eibaan
 
Papel progresistas
javier Soto
 
Java осень 2012 лекция 6
Technopark
 
JavaScript в enterprise приложениях
MoscowJS
 
商派信息安全解决方案
wanglei999
 
Pjudicial-Dfortunato
sofialucia
 
Java AWT Calculadora
jubacalo
 

Viewers also liked (13)

PDF
C++ Programming - 9th Study
Chris Ohk
 
PDF
C++ Programming - 8th Study
Chris Ohk
 
PDF
C++ Programming - 10th Study
Chris Ohk
 
PDF
C++ Programming - 7th Study
Chris Ohk
 
PDF
C++ Programming - 12th Study
Chris Ohk
 
PDF
C++ Programming - 11th Study
Chris Ohk
 
PDF
Data Structure - 2nd Study
Chris Ohk
 
PDF
C++ Programming - 14th Study
Chris Ohk
 
PDF
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
Chris Ohk
 
PDF
Data Structure - 1st Study
Chris Ohk
 
PDF
[C++ Korea 2nd Seminar] C++17 Key Features Summary
Chris Ohk
 
PDF
[C++ Korea 3rd Seminar] 새 C++은 새 Visual Studio에, 좌충우돌 마이그레이션 이야기
Chris Ohk
 
PDF
[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준)
Sang Don Kim
 
C++ Programming - 9th Study
Chris Ohk
 
C++ Programming - 8th Study
Chris Ohk
 
C++ Programming - 10th Study
Chris Ohk
 
C++ Programming - 7th Study
Chris Ohk
 
C++ Programming - 12th Study
Chris Ohk
 
C++ Programming - 11th Study
Chris Ohk
 
Data Structure - 2nd Study
Chris Ohk
 
C++ Programming - 14th Study
Chris Ohk
 
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
Chris Ohk
 
Data Structure - 1st Study
Chris Ohk
 
[C++ Korea 2nd Seminar] C++17 Key Features Summary
Chris Ohk
 
[C++ Korea 3rd Seminar] 새 C++은 새 Visual Studio에, 좌충우돌 마이그레이션 이야기
Chris Ohk
 
[Td 2015]디버깅, 어디까지 해봤니 당신이 아마도 몰랐을 디버깅 꿀팁 공개(김희준)
Sang Don Kim
 
Ad

More from Chris Ohk (20)

PDF
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍
Chris Ohk
 
PDF
고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
Chris Ohk
 
PDF
Momenti Seminar - 5 Years of RosettaStone
Chris Ohk
 
PDF
선린인터넷고등학교 2021 알고리즘 컨퍼런스 - Rust로 알고리즘 문제 풀어보기
Chris Ohk
 
PDF
Momenti Seminar - A Tour of Rust, Part 2
Chris Ohk
 
PDF
Momenti Seminar - A Tour of Rust, Part 1
Chris Ohk
 
PDF
Evolving Reinforcement Learning Algorithms, JD. Co-Reyes et al, 2021
Chris Ohk
 
PDF
Adversarially Guided Actor-Critic, Y. Flet-Berliac et al, 2021
Chris Ohk
 
PDF
Agent57: Outperforming the Atari Human Benchmark, Badia, A. P. et al, 2020
Chris Ohk
 
PDF
Proximal Policy Optimization Algorithms, Schulman et al, 2017
Chris Ohk
 
PDF
Trust Region Policy Optimization, Schulman et al, 2015
Chris Ohk
 
PDF
Continuous Control with Deep Reinforcement Learning, lillicrap et al, 2015
Chris Ohk
 
PDF
GDG Gwangju DevFest 2019 - <하스스톤> 강화학습 환경 개발기
Chris Ohk
 
PDF
[RLKorea] <하스스톤> 강화학습 환경 개발기
Chris Ohk
 
PDF
[NDC 2019] 하스스톤 강화학습 환경 개발기
Chris Ohk
 
PDF
C++20 Key Features Summary
Chris Ohk
 
PDF
[델리만주] 대학원 캐슬 - 석사에서 게임 프로그래머까지
Chris Ohk
 
PDF
디미고 특강 - 개발을 시작하려는 여러분에게
Chris Ohk
 
PDF
청강대 특강 - 프로젝트 제대로 해보기
Chris Ohk
 
PDF
[NDC 2018] 유체역학 엔진 개발기
Chris Ohk
 
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍
Chris Ohk
 
고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
Chris Ohk
 
Momenti Seminar - 5 Years of RosettaStone
Chris Ohk
 
선린인터넷고등학교 2021 알고리즘 컨퍼런스 - Rust로 알고리즘 문제 풀어보기
Chris Ohk
 
Momenti Seminar - A Tour of Rust, Part 2
Chris Ohk
 
Momenti Seminar - A Tour of Rust, Part 1
Chris Ohk
 
Evolving Reinforcement Learning Algorithms, JD. Co-Reyes et al, 2021
Chris Ohk
 
Adversarially Guided Actor-Critic, Y. Flet-Berliac et al, 2021
Chris Ohk
 
Agent57: Outperforming the Atari Human Benchmark, Badia, A. P. et al, 2020
Chris Ohk
 
Proximal Policy Optimization Algorithms, Schulman et al, 2017
Chris Ohk
 
Trust Region Policy Optimization, Schulman et al, 2015
Chris Ohk
 
Continuous Control with Deep Reinforcement Learning, lillicrap et al, 2015
Chris Ohk
 
GDG Gwangju DevFest 2019 - <하스스톤> 강화학습 환경 개발기
Chris Ohk
 
[RLKorea] <하스스톤> 강화학습 환경 개발기
Chris Ohk
 
[NDC 2019] 하스스톤 강화학습 환경 개발기
Chris Ohk
 
C++20 Key Features Summary
Chris Ohk
 
[델리만주] 대학원 캐슬 - 석사에서 게임 프로그래머까지
Chris Ohk
 
디미고 특강 - 개발을 시작하려는 여러분에게
Chris Ohk
 
청강대 특강 - 프로젝트 제대로 해보기
Chris Ohk
 
[NDC 2018] 유체역학 엔진 개발기
Chris Ohk
 
Ad

C++ Programming - 13th Study

  • 3. 3
  • 6. 6 try { // 익셉션이 발생할 코드 } catch (exception-type1 exception-name) { // type1 익셉션을 받아서 처리할 코드 } catch (exception-type2 exception-name) { // type2 익셉션을 받아서 처리할 코드 } // 나머지 코드
  • 7. 7
  • 8. 8 int Divide(int num, int den) { return num / den; } int main() { cout << Divide(5, 2) << endl; cout << Divide(10, 0) << endl; cout << Divide(3, 3) << endl; }
  • 9. int Divide(int num, int den) { if (den == 0) throw invalid_argument("Divide by zero"); return num / den; } int main() { try { cout << Divide(5, 2) << endl; cout << Divide(10, 0) << endl; cout << Divide(3, 3) << endl; } catch (const invalid_argument& e) { cout << "Caught exception: " << e.what() << endl; } } 9
  • 10. 10 void readFile(const string& fileName, vector<int>& dest) { ifstream istr; int temp; istr.open(fileName.c_str()); // 값을 하나씩 읽어서 vector에 저장 while (istr >> temp) dest.push_back(temp); } int main() { vector<int> myInts; const string fileName = "numbers.txt"; readFile(fileName, myInts); for (size_t i = 0; i < myInts.size(); i++) cout << myInts[i] << " "; cout << endl; }
  • 11. 11 void readFile(const string& fileName, vector<int>& dest) { ifstream istr; int temp; istr.open(fileName.c_str()); if (istr.fail()) throw exception(); // 값을 하나씩 읽어서 vector에 저장 while (istr >> temp) dest.push_back(temp); } int main() { vector<int> myInts; const string fileName = "numbers.txt"; try { readFile(fileName, myInts); } catch (const exception& e) { cerr << "Unable to open file " << fileName << endl; return 1; } for (size_t i = 0; i < myInts.size(); i++) cout << myInts[i] << " "; cout << endl; }
  • 12. 12 int Divide(int num, int den) { if (den == 0) throw "Divide by zero"; return num / den; } int main() { try { cout << Divide(5, 2) << endl; cout << Divide(10, 0) << endl; cout << Divide(3, 3) << endl; } catch (const string& s) { cout << s.c_str() << endl; } } 익셉션으로 던질 데이터의 타입이 변경되면 catch 구문도 수정해야 함
  • 13. 13 void readFile(const string& fileName, vector<int>& dest) { ifstream istr; int temp; istr.open(fileName.c_str()); if (istr.fail()) // 파일 열기 실패에 따른 익셉션 throw invalid_argument(""); // 값을 하나씩 읽어서 vector에 저장 while (istr >> temp) dest.push_back(temp); if (istr.eof()) istr.close(); else { // 알 수 없는 오류에 의한 익셉션 istr.close(); throw runtime_error(""); } } try { readFile(fileName, myInts); } catch (const invalid_argument& e) { cerr << "Unable to open file " << fileName << endl; return 1; } catch (const runtime_error& e) { cerr << "Error reading file " << fileName << endl; return 1; }
  • 14. 14 void readFile(const string& fileName, vector<int>& dest) throw (invalid_argument, runtime_error) { … } void readFile(const string& fileName, vector<int>& dest) throw (invalid_argument, runtime_error); void readFile(const string& fileName, vector<int>& dest) throw(); // C++98 void readFile(const string& fileName, vector<int>& dest) noexcept; // C++11
  • 16. 16
  • 17.  bad_alloc  bad_cast  bad_typeid  bad_exception  logic_error  out_of_range, invalid_argument, length_error  runtime_error  range_error, overflow_error, underflow_error 17
  • 19. 19
  • 20. 20 void f1() { throw 0; } void f2() { f1(); } void f3() { f2(); } void f4() { f3(); } int main() { try { f4(); } catch (int e) { cout << e << endl; } } 함수 호출 스택 풀기
  • 21. 21 void funcOne() throw(exception) { string str1; string* str2 = new string(); funcTwo(); delete str2; } void funcTwo() throw(exception) { ifstream istr; istr.open("fileName"); throw exception(); istr.close(); } int main() { try { funcOne(); } catch (const exception& e) { cerr << "Exception caught!" << endl; return 1; } } 예외 발생 실행 X → 지역 변수는 소멸자 실행 실행 X → 포인터 변수는 메모리 릭 발생
  • 23. 23 void funcOne() throw(exception) { string str1; string* str2 = new string(); try { funcTwo(); } catch (...) { delete str2; throw; // 익셉션 재전송 } delete str2; } “...”은 모든 타입의 익셉션을 매칭할 수 있음