at 2010-12-31
in Language, Examples, 5.8-SERIES
by friebe
(0 comments)
The new lang.Closeable interface and the io.streams classes being retrofitted to implement it may not seem very useful on the first glance, although they serve the purpose of supporting the so-called ARM blocks. These are a feature supported by XP Language and reuse the try keyword:
try ($expression[, $expression[, ...]]) { } Any of the expressions are expected to be instanceof lang.Closeable and their close() methods are guaranteed to be called in the declaration order regardless of whether the block raises an exception or not.
Example Here's a small demonstration of how it works:
import static util.cmd.Console.writeLine; public class AutoClose { public static void main(string[] $args) { $c= new Closeable() { public void close() { writeLine('Closing'); } }; try ($c) { writeLine('Inside try, args.length= ', $args.length); if ($args.length > 0) throw new IllegalArgumentException($args[0]); } } } If invoked with no arguments, no exception will be raised:
$ xp AutoClose Inside try, args.length= 0 Closing
If we pass an argument, an IAE will be raised with the argument as its message:
$ xp AutoClose Hello Inside try, args.length= 1 Closing Uncaught exception: Exception lang.reflect.TargetInvocationException (AutoClose::main() invocation failed)
This is especially useful when working with streams - we should close them regardless of what happens. Of course we could wait for their destructor to be called by PHP's garbage collection, but here's our shorthand for it, following the motto of the less code you write the less can be broken
|
Subscribe
You can subscribe to the XP framework's news by using RSS syndication.
CategoriesNews General PHP5 Announcements RFCs Further reading Examples Editorial EASC Experiments Unittests Databases 5.8-SERIES Unicode Language 5.9-SERIES
RelatedFind related articles by a search for «The».
|