Java Programming/Keywords/try

try is a keyword.

It starts a try block. If an Exception is thrown inside a try block, the Exception will be compared to any of the catch part of the block. If the Exception matches with one of the Exceptions in the catch part, the exception will be handled there.

Three things can happen in a try block:

  • No exception is thrown:
    • the code in the try block
    • plus the code in the finally block will be executed
    • plus the code after the try-catch block is executed
  • An exception is thrown and a match is found among the catch blocks:
    • the code in the try block until the exception occurred is executed
    • plus the matched catch block is executed
    • plus the finally block is executed
    • plus the code after the try-catch block is executed
  • An exception is thrown and no match found among the catch blocks:
    • the code in the try block until the exception occurred is executed
    • plus the finally block is executed
    • NO CODE after the try-catch block is executed

For example:

Computer code
public void method() throws NoMatchedException
 {
   try {
     //...
     throw new '''MyException_1'''();
     //...
   } catch ( MyException_1 e ) {
     // --- '''Handle the Exception_1 here''' --
   } catch ( MyException_2 e ) {
     // --- Handle the Exception_2 here --
   } finally {
     // --- This will always be executed no matter what --
   }
   // --- Code after the try-catch block
 }

How the catch-blocks are evaluated see Catching Rule

See also: