Title: Exceptions and I/O Summary
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Exceptions and I/O Summary

Exceptions Basics

- Programming without Exceptions (in languages that don't have exceptions like C)
- Demonstrating the occurence of an ArithmeticException (Divide by 0), and catching it
- Demonstrating getting an exception from bad user inputs to the Scanner nextInt method. Also showing how to use the exception to recover from the problem by letting the user enter the number in again.
- Exceptions can be caught locally or globally.
- Comparing exception handling strategies: "readCarefully", or "readAtYourRisk" and catch the errors globally.

Exception Heirarchy and Strategy

- Class Heirarchy: Throwable, Exception, RuntimeException, etc.
- Unchecked Exceptions (those derived from RuntimeException), versus Checked Exception (not derived from RuntimeException).
- Example to demonstrate 3 Exception handling philosophies (there are other approaches as well)
  - "Evel Knievel" programming style (ignore Exceptions)
  - Global Handling of Exceptions
  - Local Handling of Exceptions to collect more information, but pass the error on to more global routines
  - Local Handling of Exceptions to try to recover from the error locally in order to continue excecuting
- Methods available in the Throwable class (and availabe to all Exceptions classes)
  - getMessage, toString - to print out the error
  - printStackTrace(), printStackTrace(System.out) - to dump the program locations to the standard error stream or the standard system out stream

Checked Exceptions, Input/Output

- Using the Scanner class to read a file using FileInputStream ( it's similar to reading from the keyboard).
- Using the PrintStream class to produce output using FileOutputStream( it's similar to writing to System.out).
- Checked exceptions occur with most file input/output. Checked exceptions need to be caught or else a compiler occurs.
- Instead of catching an exception, you can "pass the buck" and pass the exception back to the caller with a statement like: throws FileNotFoundException
- The "finally" clause can be used to make sure that something happens before exitting a "try" block.
- Writing code that throws an Exception to prevent user's from improperly using your program. This is demonstrated in the Game-of-Life program. Note that the type of exception you choose can be checked or not-checked. You can even create and throw your own unique Exception class in order to store extra information.

Last Modified: June 1, 2014 4:08 PM