|
■概要
・例外処理は、"try","throw","catch"の3つキーワードで構成されています。
・catch文に複数同一型は定義できません。
・対象のcatch文が実行されると、他のcatch文は実行されません。
・デフォルト例外は"catch(...)"で定義します。どのcatch文にもヒットしなかった場合に実行されます。
■通常例外処理
【通常例外】
// 通常例外
int main(){
try{
throw "例外発生\n";
printf("ここは実行されません\n");
}catch(char *str){
printf("%s",str);
}catch(int int_i){
printf("%d",int_i);
}catch(long long_l){
printf("%d",long_l);
}
return 0;
}
|
■例外出力型指定
・メソッドに対して、throwできる変数の型を指定することができます。
・指定以外の型をthrowした場合、異常終了(unexpected())します。
※unexpected関数は、terminate()関数を呼び出し、プログラムを異常終了させます。
【例外出力型指定】
// 例外出力型指定
void func_sub(){
throw "文字列型例外";
}
void func() throw (int ,long){
func_sub();
}
void main(){
try{
func();
}catch(char *str){
printf("%s",str);
}catch(int int_i){
printf("%d",int_i);
}catch(long long_l){
printf("%d",long_l);
}
}
|
|