Java Keyword: try

The try keyword is used to open a block of code that potentially throw exceptions.

try {
    // code that may throw exceptions
} catch (SomeException ex) {
    // handle exception
}

There can be no catch block without a preceeding try block, which means that if an exception is thrown outside of a try block, it can’t be caught and it will cause the method to return exceptionally.

See Java Exceptions: Throw, Try and Catch for details on semantics.

Try-With-Resources

Try can also be used for automated resource management (ARM):

try (FileWriter w = new FileWriter("file.txt")) {
    w.write("Hello World");
}

The “resource” (the FileWriter in the snippet above) must implement the AutoCloseable interface. See Java: Try-With-Resources for further details.

Comments