สมมติว่ามีฟังก์ชันที่คำนวณการดำเนินการทางคณิตศาสตร์ที่ซับซ้อน ระหว่างดำเนินการอาจเกิดข้อยกเว้น (exceptions) เราต้องจัดการข้อยกเว้นประเภทต่างๆ ดังนี้:
- ถ้าหน่วยความจำไม่เพียงพอ (bad_alloc) ให้พิมพ์ 'Memory Low!'
- ถ้าเป็นข้อยกเว้นมาตรฐาน C++ อื่นๆ ให้พิมพ์ 'Exception:' ตามด้วยรายละเอียด
- ถ้าเป็นข้อยกเว้นอื่นๆ ให้พิมพ์ 'Unhandled Exception'
เราได้รับอาเรย์ที่มีคู่ค่า และส่งเข้าไปในฟังก์ชัน ถ้ามีข้อยกเว็นให้จัดการ มิฉะนั้นพิมพ์ผลลัพธ์
เช่น หาก arr = {{361643035132, 2297873642249}, {-17, 15}} ผลลัพธ์จะเป็น:
Memory Low! Exception: val1 is negative
คู่แรกใหญ่เกินจนหน่วยความจำไม่พอ คู่ที่สองค่าแรกเป็นลบ ฟังก์ชันโยนข้อยกเว้น 'val1 is negative'
ขั้นตอนการแก้ปัญหา
- วนลูปผ่านทุกคู่ค่า:
- val1 := values[i][0], val2 := values[i][1]
- try { พิมพ์ foo(val1, val2) }
- catch (bad_alloc) { พิมพ์ "Memory Low!" }
- catch (exception &e) { พิมพ์ "Exception: " + e.what() }
- catch (...) { พิมพ์ "Unhandled Exception" }
ตัวอย่างโค้ด
#include <iostream> #include <exception> #include <string> #include <stdexcept> #include <vector> #include <cmath> using namespace std; class Solution { private: static int value; public: static int foo(long long val1, long long val2) { value += 1; if(val1 < 0) throw std::invalid_argument("val1 is negative"); vector<int> vectorList(val1, 0); int r = -1, c = sqrt(-1); if(val2 == 0) throw 0; r = (val1 / val2) * r; int ans = vectorList.at(val2); return r + val1 - val2 * ans; } static int getVal() { return value; } }; int Solution::value = 0; void solve(int t, long int values[][2]) { for (int i = 0; i < t; i++) { long long val1, val2; val1 = values[i][0]; val2 = values[i][1]; try { cout << Solution::foo(val1, val2) << '\n'; } catch (const std::bad_alloc&) { cout << "Memory Low!\n"; } catch (const std::exception& e) { cout << "Exception: " << e.what() << '\n'; } catch (...) { cout << "Unhandled Exception\n"; } } } int main() { long int arr[][2] = {{361643035132, 2297873642249}, {-17, 15}}; solve(2, arr); }
อินพุต
long int arr[][2] = {{361643035132, 2297873642249}, {-17, 15}}; solve(2, arr);
เอาต์พุต
Memory Low! Exception: val1 is negative