Tutorial 21. Exceptions

exceptionはランタイムエラーのような例外を処理するための機能です。
exceptionは以下の形式で定義されます。

try compound_statement catch parameter compound_statement ...

try blockは、tryから始まるcompound statementです。try block内で例外がthrowされた場合、try blockの処理は直ちに終了されcatch blockへと移行します。
catch blockは、catchから始まるcompound statementです。一つのtry blockに対応したcatchは必ず一つ以上となり、parameterによって処理する例外が分けられます。parameterでは一つのargumentを定義するか、あるいは空のparameterのみが有効となります。
また、例外が発生しなかった場合はcatch blockの処理は行われず次のstatementへ移行します。

try{
    throw 20;
}
catch(int e){
    using::write("catch "+e+"\n");
}


throw statementはjump statementの一種で例外を発生させます。
throw 20では20が例外としてcatchが呼ばれます。例ではcatch(int e)が対応して、"catch 20"と出力されることが期待されます。

nil throw_this(){
    throw "\"throw this\"";
}

try{
    throw_this();
}
catch(int e){
    //ignore this
}
catch(string e){
    using::write("catch "+e+"\n");
}


catchはtry block内で起きたあらゆる例外を受け取ります。例ではtry内で呼ばれたthrow_this()が"\"throw this\""を例外としてthrowしています。
この例外はstring型をthrowしているので、catch(int e)では受け取ることが出来ませんが、catch(string e)によって受け取られます。

try{
    throw_this();
}
catch(){
    using::write("catch anyway\n");
}

catch()はdefault handlerで、全ての例外を受け取ることが出来ます。例では、throw_thisで発生した例外もcatch()によって処理されます。

try{
    try{
        throw_this();
    }
    catch(int e){
        //must be ignored
    }
}
catch(string e){
    using::write("catch "+e+"\n");
}


catchによって受け取られなかった例外は、そのまま上位のhandlerへとthrowされます。
この例ではthrow_thisによって発生した例外はcatch(int e)では受け取ることが出来ないので、例外はさらに上のtry block
処理されることになります。よって、catch(string e)がthrow_thisで発生した例外を処理することとなります。


Next:
Prev: Tutorial 20. Advanced Data Structures: hash