|Home | Tutorial | Classes | Functions | QSA Workbench | Language | Qt API | QSA Articles Qt Script for Applications

[Prev: throw] [Home] [Next: while]

try

try {
    Statements;
}
catch ( e ) {
}

try {
    Statements;
}
finally {
}

The try keyword is used to identify a statement block for which exceptions will be caught. There are two kinds of try block, try...catch and try...finally.

try...catch

If an exception occurs within a try...catch block, control is passed to the first catch block. If that catch block does not accept the exception, control is passed on to the next catch block (if any), and so on, until there are no more catch blocks, in which case the exception is passed up the call chain until an enclosing catch block is found to accept it, or if none accept it, the program will terminate.

A catch block has the form:

    catch ( e ) { /* statements */ }

try...finally

If an exception occurs within a try...catch block, control is passed to the finally block. This is useful if you want to ensure that something happens at the end of the block, no matter what.

Examples:

    try {
        file = new File;
        file.open( filename );
        process( file );
    }
    finally {
        file.close();   
    }

In this example, the file is always closed, even if an exception occurred.

    try {
        var a = monthToName( 11 );
        var b = monthToName( 2 );
    }
    catch ( e ) {
        if ( e == "month number out of range" ) {
            debug( "Code error: " + e );
        }
        else {
            throw e;
        }
    }

In this example, the monthToName() function is called to set two variables. If the function fails, it throws an exception rather than returns an error value, so no explicit check for an error value is necessary. If one of the function calls failed debug() is called; otherwise the exception is re-thrown so that it can be handled at a higher level. (See throw for the definition of monthToName().)

[Prev: throw] [Home] [Next: while]


Copyright © 2001-2006 TrolltechTrademarks
QSA version 1.1.5