try-with-resources
Cangjie uses try-catch-finally expressions to handle exceptions, as do many common languages. However, Cangjie provides try-with-resources syntax to automatically release non-memory resources.
Unlike with ordinary try
-expressions, try-with-resources expressions do not require catch
- and finally
-blocks. One or more variables can be listed between the try
keyword and the subsequent block to make these resource objects be automatically managed in the try-with-resources expression. When a resource exception occurs or control leaves the try-with-resources expression, the resource objects are automatically released to ensure resource security.
In the following example, the input and output variables are automatically managed in the try-with-resources expression. As such, the developer never needs to pay attention to resource release.
try (input = MyResource(),
output = MyResource()) {
while (input.hasNextLine()) {
let lineString = input.readLine()
output.writeLine(lineString)
}
}
The resource object type (MyResource
in the preceding example) must implement the Resource
interface, and specifically the isClosed
and close
functions required by the Resource
interface. isClosed
lets us check whether the resource has been released, and close
implements the release of resource operations. When an exception occurs or the try
-block ends normally, the compiler calls the corresponding function to automatically release resources.