ComeçarComece de graça

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.

Este exercício faz parte do curso

Data Types and Exceptions in Java

Ver curso

Instruções do exercício

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

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

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");
	}
}
Editar e executar o código