Prev | Current Page 363 | Next

L. McColl-Sylvester and F. Ponticelli

"Professional haXe and Neko"


Catching an Exception
Exceptions are a little like buses. You know one will appear at some point, though you wouldn ??™ t like to
hazard a guess at when, and when it does arrive, it ??™ ll quickly be followed by several others. The nice
thing about this simile, though, is that all you have to do to catch one is to stick out your thumb. Well,
okay, not quite, but it ??™ s certainly no harder than that.
So, how are exceptions caught? Ironically, you catch them with the catch keyword, but to catch them,
you must first try a block of code using the try keyword. Here ??™ s a look at this using the previous
example:
class CaughtException
{
public static function main()
{
try
{
var t : Array < String > ;
t.push(???me???);
}
catch ( err : String )
{
trace( err );
}
}
}
As you can see, the only difference between this example and the previous one is that you ??™ ve now
surrounded the original content of main with a try block and then proceeded that with a catch block.
Now, when run, the virtual machine should attempt to execute the two lines of code, and then if an
exception arises, it will be caught with the catch block and dealt with.


Pages:
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375