Exceptions

Exceptions = use to signal/indicate problems (not necessarily errors)

Some Causes:

  1. Code or Data Errors
    • use array index out of bounds.
  2. Standard Method Exceptions
    • some methods defined to "throw" exceptions
  3. Throwing your own Exceptions
    • define your own method and have it throw an exception
    • e.g. readFile() throws IOException
  4. Java Errors
    • run time errors (usually can't catch)

The Class Hierarcy

Object

Throwable

Exception                     Error

can catch               you can't catch

 


Handling Exceptions

using try, catch, finally

  • try
    • encloses code that can lead to 1 or more exceptions
    • such code must always be inside a try statement (or the method it is inside of must be declared to throw these exceptions)
  • catch
    • follows a try block and contains code to handle the exception. has parameter exception thrown.
    • can have multiple catch blocks.....each one handling a different Exceptions
    • If you have catches for Exceptions in the same heirarchy chain, put in order of lowest subclass first...otherwise, will never catch the lower subclass Exceptions.
      • E.g.
      • try { }
      • catch (Arithmetic Exception e)
      • { ....}
      • catch (Exception e)
      • {....}
  • finally
    • follows any catch block and is always exceuted no mater what
    • e.g. use to close streams
    • optional.

     

Re-throwing an exception

  • you can rethrow an exception ....in a sense returns it from the method you are in
  • e.g.
    • try{ ....}
    • catch(IOExceoption e)
    • { throws e; }


Creating your Own Exception Class and Thowing It

  1. Create a subclass of Exception and you should have a default constructor and a constructor with 1 string argument
  2. Create instance of this new class....lets call it P.
  3. Then trow P..... throw P; as appropriate in your code

© Lynne Grewe