GiaoTrinhC++(27Jun21)

(Hoang2711) #1
Ngôn ngữ lập trình C++

Tin Học Cho Mọi Người • 63

Ví dụ: #include
using namespace std;
int main() {
try { int age = 15;
if (age >= 18) { cout << "Access granted - you are old enough."; }
else { throw "You are too young!"; } }
catch (string something) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Error occurs for " << something; } return 0; }
Kết quả: terminate called after throwing an instance of 'char const*'


Nhưng nếu bạn gán chuỗi đó vào một biến chuỗi, rồi throw ném ra biến chuỗi đó thì catch sẽ bắt
gọn hơ như trong ví dụ sau.


Ví dụ: #include
using namespace std;
int main() {
try { int age = 15; string mymsg = "You are too young!";
if (age >= 18) { cout << "Access granted - you are old enough."; }
else { throw mymsg; } }
catch (string something) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Error occurs for " << something; } return 0; }


Kết quả: Access denied - You must be at least 18 years old.Error occurs for You are too young!

6. Xử lý bất kỳ loại ngoại lệ nào (...)


Nếu bạn không biết chắc loại dữ liệu nào được throw ném ra trong khối try, bạn có thể sử dụng
cú pháp "ba dấu chấm" (...) bên trong khối catch, sẽ xử lý bất kỳ loại ngoại lệ nào (số, chuỗi, kể
cả trực kiện chuỗi):


Ví dụ: #include
using namespace std;
int main() { int x;
cout << "how many years old? "; // gõ vào một số và nhấn enter
cin >> x;
// nhận trị do người dùng nhập vào
try { int age = x;
if (age >= 18) { cout << "access granted - you are old enough."; }
else { throw "You are too young!"; } }
catch (...) {
cout << "access denied - you must be at least 18 years old."; }
return 0; }
Kết quả: how many years old? 15access denied - you must be at least 18 years old.

Free download pdf