Sabtu, 17 April 2010

Cpp eksepsi

#include

using namespace std;

namespace exception{
struct error{
const char *p;
error(const char *q){
p = q;
}
};
}

class Eksepsi{

public:
Eksepsi(){
/*konstruktor*/

}

void eksepsiThrowStandar(int kode){
if(kode < 1){

throw exception::error("error code");
}
}

void eksepsiThrowSendiri(int kode){
if(kode < 1){


throw exception::error("error");
}
}

void eksepsiThrowIndexOutOfBounds(int jumlah, int index, int nilai, int *tab){
if((jumlah-1) < index){
throw exception::error("array index out of bounds");
}
else{
(*tab) = nilai;
}
}

};


int main(){

Eksepsi eks;
int tabInt[10];

printf("eksepsi throw standar \n");

/*eksepsi throw standar*/
try{

eks.eksepsiThrowStandar(-1);

}
catch(exception::error e){

printf("%s\n", e.p);

}

printf("-------------------------\n");

printf("eksepsi throw sendiri\n");

/*eksepsi throw dengan kalimat sendiri*/
try{

eks.eksepsiThrowSendiri(-1);

}
catch(exception::error e){

printf("%s\n", e.p);

}

printf("-------------------------\n");

printf("eksepsi try catch\n");

/*eksepsi try catch karena mengakses indeks array lebih dari jumlah tempat array*/
try{

eks.eksepsiThrowIndexOutOfBounds(10, 10, 10, &tabInt[10]);
}
catch(exception::error e){

printf("%s\n", e.p);

}

printf("-------------------------\n");

return 0;

}