Professional Documents
Culture Documents
Opt1 FRESHER
Assignment topic: Exception Handling
ACADEMY
Assignment duration: 120 minutes
try
{
if (x < 0.0)
throw "Không thể lấy hàm sqrt của số âm";
cout << "Hàm sqrt của " << x << " là " << sqrt(x) << '\n';
}
catch (const char* exception)
{
cout << "Error: " << exception << '\n';
}
}
int main() {
try
{
int* myarray = new int[1000];
cin >> *myarray;
}
catch (exception& e)
{
cout << "Standard exception: " << e.what() << endl;
}
catch (length_error& le)
{
cout << "Length error" << le.what() << '\n';
}
return 0;
}
void throw_nested() {
try {
throw std::logic_error("first");
}
catch (const std::exception& e) {
std::throw_with_nested(std::logic_error("second"));
}
}
int main() {
try {
throw_nested();
}
catch (std::exception& e) {
print_what(e);
}
return 0;
}
#include <iostream>
int main()
if (b == 0)
c = a / b;
return 0;
“Special exception”
#include <iostream>
int main()
{
int ex = x[i];
try
if (_ex != x[i]____)
throw ex;
else
throw 'ex';
catch (_...___)
return 0;
#include <iostream>
#include <exception>
using namespace std;
int main() {
long long i = _-1____;
try
{
char* text = __new char[i]__;
}
catch (bad_alloc& e)
{
cout << "X";
}
catch (exception& e)
{
cout << "Y";
}
catch (...)
{
cout << "Z";
}
return 0;
}
Bài 4:
#include <string.h>
#include <iostream>
using namespace std;
int dem(int n) {
int sum = 1;
for (int i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
int main() {
int n;
cin >> n;
cout << dem(n);
return 0;
}
Bài 5:
#include <iostream>
struct toado {
double x;
double y;
void khoitao() {
cin >> x >> y;
}
};
if (sqrt(a) < sqrt(b) + sqrt(c) || sqrt(b) < sqrt(a) + sqrt(c) || sqrt(c) <
sqrt(a) + sqrt(b))
{
if (a == b + c || b == a + c || c == a + b)
{
if (a == b || b == c || c == a)
cout << "Day la tam giac vuong can";
else cout << "Day la tam giac vuong";
}
else if (a == b && b == c)
cout << " Day la tam giac deu";
else if (a == b || b == c || c == a)
cout << " Day la tam giac can";
else if (a * a > b * b + c * c || b * b > c * c + a * a || c * c > a * a +
b * b)
cout << " Day la tam giac tu";
else
cout << "Day la tam giac nhon";
}
else
cout << " 3 diem nay khong tao nen tam giac";
}
int main() {
toado a, b, c;
a.khoitao();
b.khoitao();
c.khoitao();