Exceptions = use to signal/indicate problems (not necessarily errors)
Some Causes:
|
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
- Create a subclass of Exception and you should have a default constructor and a constructor with 1 string argument
- Create instance of this new class....lets call it P.
- Then trow P..... throw P; as appropriate in your code