class
Exceptions in Constructors
In this example we shall show you how to handle exceptions in constructors. To handle exceptions in constructors we have performed the following steps:
- We have created a class,
InputFile, that has a BufferedReader field. - In its constructor, it gets a String and it creates a new FileReader with the given String name of path to file to read from. A FileNotFoundException might be thrown here, that needs to be caught, but since the file is not found the BufferedReader is not opened so does not need to close.
- If any other exception occurs after that, the FileReader has opened so it has to close.
- The
InputFileclass also has two methods,getLine(), that gets the line of the text in the BufferedReader, anddispose()that closes the BufferedReader. The methods throw RuntimeException that has to be caught. - We create a new instance of
InputFile, with a given String. Since the constructor of the class is called if the file is not found the exception will be thrown,
as described in the code snippet below.
package com.javacodegeeks.snippets.core;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ExceptionInConstructor {
public static void main(String[] args) {
try {
InputFile inputFile = new InputFile("Cleanup.java");
String string;
int i = 1;
while ((string = inputFile.getLine()) != null)
; // Perform line-by-line processing here...
inputFile.dispose();
} catch (Exception e) {
System.err.println("Caught Exception in main");
e.printStackTrace();
}
}
}
class InputFile {
private BufferedReader input;
public InputFile(String fileName) throws Exception {
try {
input = new BufferedReader(new FileReader(fileName));
// Other code that might throw exceptions
} catch (FileNotFoundException e) {
System.err.println("Could not open " + fileName);
// Wasn't open, so don't close it
throw e;
} catch (Exception e) {
// All other exceptions must close it
try {
input.close();
} catch (IOException e2) {
System.err.println("in.close() unsuccessful");
}
throw e; // Rethrow
} finally {
// Don't close it here!!!
}
}
public String getLine() {
String s;
try {
s = input.readLine();
} catch (IOException e) {
throw new RuntimeException("readLine() failed");
}
return s;
}
public void dispose() {
try {
input.close();
System.out.println("dispose() successful");
} catch (IOException e2) {
throw new RuntimeException("in.close() failed");
}
}
}
Output:
dispose() successful
This was an example of how to handle exceptions in constructors in Java.
