Wiki
Version 5 (modified by hopscc, 12 years ago)

--

Try/Catch

A statement that specifies to run (try) a block of code and to trap (catch) and handle any exceptions thrown from it.

Exceptions can be specified to be trapped in one of three ways

  • catch exception type and capture the exception instance for use in its corresponding catch block.
  • catch exception type ignoring actual instance
  • catchAll clause - catch any exceptions not already given

There can be multiple catch clauses given specifying different exceptions to trap but there can be only one 'catchAll' clause.

The success clause is optional and if specified is executed only if no catch clauses are invoked (i.e if no catch specified exceptions are thrown).

The finally clause is also optional and if specified is invoked after all other clauses regardless of whether any exceptions were thrown, trapped and/or rethrown. Control is always passed to any finally block regardless of how the try block exits.

Whereas catch clauses are used to handle exceptions that occur in a statement block, finally is used to guarantee a statement block of code executes regardless of how the preceding try block is exited. Used for must-cleanup situations (see also Using).

Grammar

try
    <statements>
catch <VarName> as <exceptionType>  (*1)   or
catch <exceptionType>               (*2)   or
catch                           (*3)
    <statements>    
[success                         (*4)
    <statements> ]

[finally                         (*4)
    <statements> ]

*1 - specify a variable to place the caught exception in to manipulate (or rethrow) within the subsequent catch codeblock

*2 - Use this form to catch a particular exceptionType when you dont need the particular exception instance. (To ignore the exception or exit for example)

*3 - Catch any and all exceptions not already specifically listed (CatchAll clause) There can be only one catchAll clause and if used it must be after all other catch clauses.

*4 - optional

Platform

Examples


# parsing numbers
s = tok.text.replace('_', '')
if s.endsWith('f')
    s = s[:-1]
try
    value = float.parse(s, Utils.cultureInfoForNumbers)
catch FormatException
    .recordError('Unexpected FormatException for float literal "[tok.text]".')
catch OverflowException
    .recordError('Range overflow for float literal "[tok.text]".')


# reading file contents
contents = 'test: failure'
try
    contents = File.readAllText('myFile.txt')
catch ioe as IOException
    print 'I/O Error: [ioe.message]'
success
    assert 'test' in contents
    
# customException
try
    if source.length==0
        _warning('File is empty.')
    else if source.trim.length==0
    _warning('File is completely blank.')
    return _parseTokens()
catch pe as ParserException
    if _errorRecorder, _errorRecorder.recordError(pe)
    _tokenizer = nil
    throw  # rethrow exception trapped above

Notes