In Java 7 and later it is possible to avoid code duplication by using a single catch block to handle more than one type of exception. The bytecode generated for a single catch block handling multiple exceptions is smaller compared to an equivalent implementation with multiple catch blocks and thus considered better for performance.
Consider a simple example to read a file with numbers and create a list of numbers. In Java 6 and earlier, we do an implementation similar to the one below. Here we repeat the same exception handling code in each of the catch blocks.
public static List<Integer> readFile(String fileName) { List<Integer> myList = new ArrayList<Integer>(); BufferedReader in = null; try { in = new BufferedReader(new FileReader(fileName)); String line = null; while ((line = in.readLine()) != null) { int num = Integer.parseInt(line); myList.add(num); } } catch (NumberFormatException e) { // do some action e.printStackTrace(); } catch (IOException e) { // do some action e.printStackTrace(); } finally { try { if ( in != null ) in.close(); } catch (IOException e) { e.printStackTrace(); } } return myList; }In Java 7 it is possible to specify a single catch block to handle multiple exceptions to eliminate duplicate code. Each of the exception types a catch block needs to handle is separated by a vertical bar "|". This implementation is considered efficient since the byte code generated is smaller.
public static List<Integer> readFileMultiCatch(String fileName) { List<Integer> myList = new ArrayList<Integer>(); BufferedReader in = null; try { in = new BufferedReader(new FileReader(fileName)); String line = null; while ((line = in.readLine()) != null) { int num = Integer.parseInt(line); myList.add(num); } } catch (NumberFormatException | IOException e) { // do some action e.printStackTrace(); } finally { try { if ( in != null ) in.close(); } catch (IOException e) { e.printStackTrace(); } } return myList; }
0 comments:
Post a Comment