LoslegenKostenlos loslegen

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.

Diese Übung ist Teil des Kurses

Data Types and Exceptions in Java

Kurs anzeigen

Anleitung zur Übung

  • 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.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

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 bearbeiten und ausführen