Chapter 10 |
New exception class
Although Java’s built-in exceptions handle most common errors, we will probably want to create our own exception types to handle situations specific to our applications. This is quite easy to do: just define a subclass of java.lang.Exception
. Our subclasses do not need to actually implement anything — it is their existence in the type system that allows us to use them as exceptions.
It is strongly recommended to choose the names of the exceptions so that it ends with Exception
. The class name should describe the nature of the exception.
Let us change the program FileReader2
so that the read lines are converted into numbers. If an exception occurs during the conversion process, then we can see some additional information about the broken line.
public class BrokenLineException extends RuntimeException { private int line; public BrokenLineException(int line, NumberFormatException myConversionException) { super("broken data on line " + line, myConversionException); this.line = line; } public int lineNumber() { return line; } } public class FileReader3 { public static void main(String[] args) throws IOException { try (BufferedReader myReader = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), "UTF-8"))) { System.out.println(readMyFile(myReader)); } catch (BrokenLineException e) { System.out.println("line number: " + e.lineNumber()); throw e; // pass the exception forward since we have nothing to do with it } } private static List<Integer> readMyFile(BufferedReader myReader) throws IOException { List<Integer> lines = new ArrayList<>(); int lineNumber = 1; while (true) { String line = myReader.readLine(); if (line == null) break; try { lines.add(Integer.parseInt(line)); lineNumber++; } catch (NumberFormatException e) { throw new BrokenLineException(lineNumber, e); } } return lines; } }
Chapter 10 |