Reading and writing filesTopExceptions in Java

Exceptions in Java

Exceptions are used in Java in the same way as Grace. Code that may throw an exception must be wrapped with a try...catch clause:

    try {
        ... code that might throw an exception
    } catch (SomeException exc) {
        ... code to handle exception ...
    }

An example is Integer.parseInt(s), which attempts to convert a string to a number. If the argument does not correspond to the decimal representation of an int then it will throw a NumberFormatException. Thus all calls to Integer.parseInt(s) should be wrapped in a try-catch clause.

Try clauses can have as many catch clauses as desired, but they are gone through from first to last, with the first one that matches being executed (and then the rest skipped):

    try {
        ... code that might throw an exception
    } catch (NumberFormatException exc) {
        code1
    } catch (Exception ex) { code2 }

If a NumberFormatException is thrown then code1 will be executed, if anything else is thrown then code2 will be executed.

What unfortunate results would we get if we interchanged the order of the two catch statements?

Here is an example of code throwing an exception:

   public Color ( int r, int g, int b ) {

      if ( r < 0 || r > MAXVALUE )
         throw new IllegalArgumentException("Color value out of range- Red");
      if ( g < 0 || g > MAXVALUE)
         throw new IllegalArgumentException("Color value out of range- Green");
      if ( b < 0 || b > MAXVALUE)
         throw new IllegalArgumentException("Color value out of range- Blue");

      this.r = r;
      this.g = g;
      this.b = b;
   }

Exceptions in Java come in two flavors: those that extend RunTimeException and those that do not. RunTimeExceptions are generally those that can arise almost anywhere, including null pointer exceptions, exceptions arising from dividing by 0, and similar things. Other examples include the NumberFormatException and IndexOutOfBoundsException

Non-RunTimeExceptions must normally be handled by the methods that throw them. If not handled there, they must be listed in the method header.


Reading and writing filesTopExceptions in Java