Đẩy nhiều phần tử vào stack Lấy phần tử ra khỏi stack rỗng. Lỗi có thể xảy ra là dạng out-of-bound.[r]
(1)(2)Ngoại lệ (Exception)
Exception gồm:
Mơ tả lỗi xảy ra.
Đoạn mã lệnh xảy exception,
nằm khối try{}
Những thứ gây exception nằm
lệnh throw
(3)Ví dụ
Trong ví dụ stack, lỗi xảy
khi:
Đẩy nhiều phần tử vào stack Lấy phần tử khỏi stack rỗng
(4)Ví dụ …
#include <stdlib.h> #include <iostream.h>
const int STACK_SIZE = 100; class stack {
protected:
int count; private:
int data[STACK_SIZE]; public:
stack(void);
void push(const int item); int pop(void);
(5)Ví dụ …
inline stack::stack(void)
{
count = 0; }
inline void stack::push(const int item) {
data[count] = item; count++;
}
inline int stack::pop(void) {
count ;
(6)Ví dụ …
const int WHAT_MAX = 80; class bound_err {
public:
char what[WHAT_MAX]; bound_err(char *_what) {
if (strlen(_what) < (WHAT_MAX -1)) strcpy(what, _what);
else
strcpy(what, "Internal error: _what is too long"); }
(7)Ví dụ …
class b_stack: public stack { public:
void push(const int item) throw(bound_err); int pop(void) throw(bound_err);
(8)Ví dụ …
inline void b_stack::push(const int item) throw(bound_err) {
if (count >= STACK_SIZE) {
bound_err overflow("Push overflows stack"); throw overflow;
}
stack::push(item); }
inline int b_stack::pop(void) throw(bound_err) {
if (count <= 0) {
throw bound_err("Pop causes stack underflow"); }
(9)Ví dụ …
b_stack test_stack; void push_a_lot(void) {
for (int i = 0; i < 5000; i++) test_stack.push(i); } main () { try { push_a_lot(); }
catch (bound_err &err) {
cout << "Error: Bounds exceeded\n"; cout << "Reason: " << err.what << '\n'; exit (8);
}
catch ( ) {
cout << "Error: Unexpected exception occurred\n"; exit (8);
}