C++에서 Error Handling은 에러가 날 부분에서 throw, throw 코드를 동작시키는 부분에서 try/catch를 통해 이루어진다.
Java와 똑같다. 그리고 당연하게도 Exception 클래스를 직접 만들 수도 있다.
아래는 학교 PPT에 나온 예제를 바탕으로 코드를 완성시켜 본 것이다.
내 git hub 에서도 찾아볼 수 있다.
https://github.com/lx5475/cpp_practice/blob/master/error_handling.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | /* Error Handling */ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> using namespace std; class StackException { protected: const string msg; public: StackException(const string& msg) : msg(msg) {}; void print() const { cout << msg << endl; } }; template <class T> class StackSizeException : public StackException { T value; public: StackSizeException(const string& msg, const T& value) : StackException(msg), value(value) {}; void print() const { cout << msg << " " << value << endl; } }; class CharStack { int size; int top; char* s; public: CharStack(int sz) { if (sz <= 0) throw StackSizeException<int>("Invalid stack size.", sz); top = 0; size = sz; s = new char[size]; } CharStack(const CharStack& charStack) { delete[] s; top = charStack.top; size = charStack.size; s = new char[size]; for (int i = 0; i < top; i++) { s[i] = charStack.s[i]; } } ~CharStack() { delete[] s; } CharStack& operator= (const CharStack& charStack) { delete[] s; top = charStack.top; size = charStack.size; s = new char[size]; for (int i = 0; i < top; i++) { s[i] = charStack.s[i]; } return *this; } void push(char c) { if (top == size) throw StackException("Stack is full."); s[top++] = c; } char pop() { if (top == 0) throw StackException("Stack is empty."); char r = s[--top]; s[top] = '\0'; return r; } void print() const { for (int i = 0; i < top; i++) { cout << s[i]; } cout << endl; } }; int main() { int SIZE = 20; CharStack cs(SIZE); // push error test cout << "<push error test>" << endl; string testChar = "Hello world, I'm Jieun."; try { for (int i = 0; i < testChar.size(); i++) { cs.push(testChar.at(i)); } } catch (const StackException& e) { e.print(); } cs.print(); // copy constructor test cout << "<copy constructor test>" << endl; CharStack cs2(cs); cs2.print(); // assignment operator test cout << "<assignment operator test>" << endl; CharStack cs3 = cs; cs3.print(); // pop error test cout << "<pop error test>" << endl; try { for (int i = 0; i < SIZE + 1; i++) { cs.pop(); } } catch (const StackException& e) { e.print(); } cs.print(); // constructor error test cout << "<constructor error test>" << endl; try { CharStack cs2(-3); } catch (const StackSizeException<int>& e) { e.print(); } } | cs |
'프로그래밍 > C | C++' 카테고리의 다른 글
Polynomial Operation in C++, 다항식 연산 덧셈/뺄셈/곱셈 (0) | 2016.10.04 |
---|