-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexception_handling.cpp
More file actions
57 lines (48 loc) · 1.21 KB
/
exception_handling.cpp
File metadata and controls
57 lines (48 loc) · 1.21 KB
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
// 1. throwing expcetion (throw)
// 2. catch
// 3. try
// stdexcept std::out_of_range std::invalid_argument std::runtime_error
//
// try {
// throw expcetion;
// } catch (tipe_exception variabel) {
// ..
// }
#include <filesystem>
#include <iostream>
#include <string>
#include <stdexcept>
class KostumException : public std::exception {
private:
std::string pesan;
public:
explicit KostumException(const std::string pesan) : pesan(pesan) {}
const char* what() const noexcept override {
return pesan.c_str();
}
};
class Kalkulator {
public:
double pembagian(double angka1, double angka2) {
if (angka2 == 0) {
throw std::invalid_argument("Error: tidak dibagikan dengan nol!");
}
return angka1 / angka2;
}
};
int main() {
Kalkulator kalkulator;
double angka1, angka2;
std::cout << "masukkan angka: ";
std::cin >> angka1;
std::cout << "masukkan angka kedua: ";
std::cin >> angka2;
try {
double hasil = kalkulator.pembagian(angka1, angka2);
std::cout << "hasilnya adalah " << hasil << std::endl;
} catch (const std::invalid_argument &pesan_error) {
std::cout << pesan_error.what() << std::endl;
}
std::cout << "hasil kalkulasi berhasil!" << std::endl;
return 0;
}