The throws keyword

Rather than explicitly catching an exception you can declare that your method throws the exception. This passes the repsonsibility to handle it to the method that invokes your method. This is done with the throws keyword. For example,

 public static void copy(InputStream in, OutputStream out) 
   throws IOException {

    byte[] buffer = new byte[256];
    while (true) {
      int bytesRead = in.read(buffer);
      if (bytesRead == -1) break;
      out.write(buffer, 0, bytesRead);
    }

  }

A single method may have the potential to throw more than one type of exception. In this case the exception clases are just separated by commas. For example,

public BigDecimal divide(BigDecimal value, int roundingMode) throws ArithmeticException, IllegalArgumentException

You can declare that your method throws runtime exceptions though you do not have to. The main use of this is as documentation for the programmer. It can also be useful in white box testing.


Previous | Next | Top | Cafe au Lait

Copyright 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified June 8, 1999