Aan de slagGa gratis aan de slag

Using finally in a real example

Finally blocks are generally used to close and clean up resources like a database or file that are being use - regardless of normal flow or whether an exception has occurred.

Here, you will simulate opening a file, writing text to the file, as well as closing the file - all with method calls. You use finally to close the simulated file regardless of whether an exception occurs.

Deze oefening maakt deel uit van de cursus

Data Types and Exceptions in Java

Cursus bekijken

Oefeninstructies

  • Begin a try block around work that opens a file and writes to the file
  • Capture any exception that might occur in opening the simulated file and writing text to it.
  • Add a finally block to close the simulated file, which will get called if the program runs without issue or if an exception occurs when opening the file or writing to the file.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

public class FinallyCleanup {

	public static void main(String[] args) {
		String[] words = { "Lorem", "ipsum", "dolor", "sit", "amet" };
		// Open a try block
		____ {
			open();
			for (int i = 0; i <= words.length; i++) {
				writeToFile(words[i]);
			}
		// Catch any possible exception
		} ____ (____ ____) {
			System.out.println("Problem writing words to file");
		// Add a finally block to close the file
		} ____ {
			close();
		}
	}

	public static void open() {
		System.out.println("Our file is open");
	}

	public static void close() {
		System.out.println("Our file is closed");
	}

	public static void writeToFile(String text) {
		System.out.println(text + " has been written to the file");
	}
}
Code bewerken en uitvoeren