9. 예외 처리
1. 예외 처리 1
#include <iostream>
#include <vector>
using namespace std;
int GetValue(vector<int> data, int index) {
if (index >= int(data.size())) {
throw index;
} else if (index < 0) {
throw "index는 0보다 크거나 같아야 합니다.";
}
return data.at(index);
}
int main() {
vector<int> data;
int value;
int index_arr[3] = {-1, 0, 1};
data.push_back(1234);
for (auto index : index_arr) {
cout << "== index = " << index << " ==" << endl;
try {
value = GetValue(data, index);
cout << "인덱스 " << index << "의 값은 "
<< value << "입니다." << endl;
} catch (int input) {
cout << "인덱스 " << input
<< "은 vector의 길이를 벗어납니다." << endl;
} catch (const char *st) {
cout << st << endl;
}
}
return 0;
}
2. 예외 처리 2
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> data;
data.push_back(1);
try {
if (data.empty() == true)
throw "벡터가 비어 있습니다.";
if (data.size() < 2)
throw 99;
} catch (char *e) {
cout << "catch (char *e) " << e << endl;
} catch (int e) {
cout << "catch (int e) " << e << endl;
}
return 0;
}
3. 예외 처리 3
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class InputError : public runtime_error {
public:
InputError(int idx, string msg) : runtime_error("") {
cout << idx << "번 인덱스에 잘못된 입력값: " << msg << endl;
}
};
int main() {
vector<int> data;
data.push_back(1);
int idx = 10;
int value = 20;
try {
if (idx >= data.size())
throw InputError(idx, to_string(value));
data.at(idx) = 99;
} catch (InputError e) {
cout << e.what();
}
return 0;
}