The finally Clause - Java Language Basics

Java examples for Language Basics:try catch finally

Introduction

finally clause includes the code that you absolutely must run, no matter what happens, regardless of whether an exception is thrown.

try { 
    readTextFile (); 
} catch  (IOException ioe) { 
    // deal with IO errors 
} finally { 
   closeTextFile (); 
} 

Example.

public class Main {
  String[] input = { "123123", "1231321", "12312fdfd" };

  public static void main(String[] arguments) {
    Main hex = new Main();
    for (int i = 0; i < hex.input.length; i++)
      hex.readLine(hex.input[i]);
  }

  void readLine(String code) {
    try {
      for (int j = 0; j + 1 < code.length(); j += 2) {
        String sub = code.substring(j, j + 2);
        int num = Integer.parseInt(sub, 16);
        if (num == 255)
          return;
        System.out.print(num + " ");
      }
    } finally {
      System.out.println("**");
    }
    return;
  }
}

Related Tutorials