Java Exceptions CSc 335 ObjectOriented Programming and Design
Java Exceptions CSc 335 Object-Oriented Programming and Design Spring 2009
Acknowledgements • These slides were written by Richard Snodgrass, using • • • slides from Rick Mercer and Marti Stepp. The slides were reorganized by Andrew Oplinger. Some material from Effective Java by Joshua Bloch, Addison-Wesley, 2008, ISBN 0 -321 -35668 -3 Improvements by Ivan Vazquez. Java Exceptions X-2
Exceptions Java API Java Language Frameworks Abstract Classes Packages Collection Exceptions Java Swing JDK/JRE Listeners Events Inversion of Control Debugging JUnit Testing & Maintaing Large Programs Eclipse Javadoc Teams PITL Layout Manager Refactoring Iterator Command Observer Observable Composite Design Patterns Coupling/ Cohesion OO Design Reading others’ code Template MVC Inheritance Hierarchy UML Class Diagrams Sequence Diagrams Package Diagrams Y-3 X-3
Motivation for Java Exceptions • Exceptions provide graceful way to handle (catch) errors as a program is executing. • They provide a means to specify distinct error-handlers over a wide range of code. • They provide standard way by which to generate (throw) an error state. • They represent fixable errors (exceptions) in a program as objects • They create an extensible inheritance hierarchy of exception classes for precise error handling. Java Exceptions X-4
Exceptions and the Call Stack Methods being called Java Exceptions Resultant Exception handling X-5
Types of Program Exceptions/Errors • Exceptions (can be handled by program): n n I/O errors (keyboard / floppy / disk / input) Network errors (internet, LAN) Illegal casting, object dereferencing (null), math Array / collection index out of bounds • Errors (cannot be handled reasonably by program): n n n Computer out of memory Java Virtual Machine bug / error / crash Corrupt Java classes required by program Java Exceptions X-6
Exception Inheritance Hierarchy • java. lang. Throwable n n Java Exceptions Error u Thread. Death u Out. Of. Memory. Error u Virtual. Machine. Error Exception u AWTException u IOException s File. Not. Found. Exception s Malformed. URLException s Remote. Exception s Socket. Exception u Runtime. Exception s Arithmetic. Exception s Class. Cast. Exception s Illegal. Argument. Exception s Index. Out. Of. Bounds. Exception s Null. Pointer. Exception s Unsupported. Operation. Exception X-7
Methods of Exception • The Exception class has several useful methods: n n n Exception(String message) - Constructor to associates a message with this exception that can be recovered later get. Message() – Returns an informative string associated with a given instance of Exception print. Stack. Trace() – Prints the stack of method calls that led up to the point at which this instance of Exception was thrown to the System. err print stream Java Exceptions X-8
Checked vs. Runtime Exceptions • Checked: n n n Could have been caused by something out of your program’s control Must be dealt with by your code, or else the program will not compile Your code must say throws … if it doesn’t explicitly handle checked exceptions that could be thrown. • Unchecked (Exception→Runtime. Exception): n n n Your fault!! (Probably) could have been avoided by “looking before you leap” in your code (testing for such errors) Need not be handled, but will crash program if a non-handled runtime exception is thrown Java Exceptions X-9
Throwing (generating) Runtime Exceptions • May be thrown at any point in code, at programmer’s • discretion Need not be caught (handled) by caller public Object get(int index) throws Index. Out. Of. Bounds. Exception { // check argument for validity if (index < 0) { throw new Index. Out. Of. Bounds. Exception("neg. index!"); } else { return my. Stuff[index]; } } Java Exceptions X-10
Throwing Checked Exceptions • Method header must specify all types of non-runtime • exceptions that it can throw. Anyone who calls the “throwing” method must now handle its exceptions, or re-throw them (pass the buck). public void read. File(String file. Name) throws IOException { if (!can. Read(file. Name)) { throw new IOException("Can’t read file! "); } else { whatever(); } } Java Exceptions X-11
Catching (Handling) Exceptions: Syntax try { code. That. Might. Crash(); } catch (Kind. Of. Exception exception. Var. Name) { // code to deal with index exception } // optional! finally { // code to execute after the try code, // or exception’s catch code, has finished running } Java Exceptions J-12
Catching Multiple Exceptions try { code. That. Might. Crash(); more. Bad. Code(); } catch (Index. Out. Of. Bounds. Exception ioobe) { // code to deal with index exception } catch (IOException ioe) { // optional; code to deal with i/o exception } catch (Exception e) { // optional; code to deal with any other exception } finally { // optional; code to execute after the try code, // or exception’s catch code, has finished running } Java Exceptions X-13
Try/Catch Example 1 try { read. File("hardcode. txt"); } catch (IOException ioe) { // code could throw IOException; must catch. // I’ll handle it by printing an error message to the user System. out. println("Unable to read file!"); } finally { // whether it succeeded or not, I want to close the file close. File(); } Java Exceptions X-14
Try/Catch Example 2 while (true) { int index = kb. read. Int(); try { Object element = my. Collection. get(index); break; // if I get here, it must have worked! } catch (Index. Out. Of. Bounds. Exception ioobe) { // wouldn’t have to catch this runtime exception. . . System. out. print("Bad index; try again. "); } } Java Exceptions X-15
Good Ways to Handle Exceptions • Print error message (System. out. println). • Pop up error box (in GUI programs). • Re-prompt user (for keyboard errors). • Try operation again (for I/O problems). • Fix or correct the error yourself (not always possible). • Re-throw exception (if you shouldn’t handle it, but perhaps someone else should). • Throw more general exception (more abstract). Java Exceptions X-16
Where to Catch an Exception • What is the logical definition of the error? • When do you have the information to handle the error? Java Exceptions R-17
Poor Exception Handling • Tiny try block (micro-management) • Huge try block • Over-general catch clause (catch Exception) • Ineffectual catch body (e. g. {}) • Catching a runtime exception where it could have been prevented by simple checking (e. g. null, index) Java Exceptions X-18
Creating Your Own Exception Class public class No. Signal. Exception extends Exception { public No. Signal. Exception(String message) { super(message); } public String to. String() { return "Your phone is out of range: " + get. Message(); } } Note: get. Message is a method of Throwable. Java Exceptions X-19
Some Points to Note • Can’t catch an Error. Why? • Exceptions occur all over the place, in n n I/O Networking / internet Remote code invocation Reflection • Making methods throw checked exceptions forces them to be used more carefully. • Cute debugging technique: new Runtime. Exception(). print. Stack. Trace(); • You can catch Exceptions in Eclipse: n Run -> Add Java Exception Breakpoint Java Exceptions X-20
To Use Exceptions, Or Not To Use Exceptions? • Java guru Joshua Bloch notes: When used to best advantage, exceptions can improve a program's readability, reliability and maintainability. When used improperly, they can have the opposite effect. • Use exceptions only for exceptional conditions. They should never be used for ordinary control flow. n Java Exceptions In other words, avoid spaghetti code. X-21
To Use Exceptions. . . (Contd. ) • Use checked exceptions for conditions from • which the caller can reasonably be expected to recover. This example forces the caller to handle the problem in the calling code. public void parse. File(File file) throws IOException, Parse. Exception { if( ! format. Correct(file)) { throw new Parse. Exception ( "Bad Format"); }. . . Java Exceptions X-22
To Use Exceptions. . . (Contd. ) • Use runtime exceptions to indicate programming • • (caller) errors. Convention dictates that errors are reserved for use by the JVM. In this example, we use Null. Pointer. Exception which extends Run. Time. Exception. public void parse. File(File file) throws IOException, Parse. Exception { if( file == null ) { throw new Null. Pointer. Exception( "null file passed. "); }. . . Java Exceptions X-23
For Reference • Core Java Ch. 11, pp. 557 -578 • The Java Tutorial: Exception-Handling. http: //java. sun. com/docs/books/tutorial/java/ nutsandbolts/exception. html • The Java Tutorial: Handling Errors with Exceptions. http: //java. sun. com/docs/books/tutorial/essential/ exceptions/index. html Java Exceptions X-24
335 Concept Map – Exceptions Type Resolution Type Checking Compile-Time Run-Time Java API Java Language Frameworks Abstract Classes Packages Collection Anonymous Classes Exceptions Java Swing JDK/JRE Listeners Events Inversion of Control MVC Debugging JUnit Testing & Maintaing Large Programs Eclipse Javadoc Teams PITL Java Exceptions Inheritance Hierarchy Iterator Design Patterns Coupling/ Cohesion OO Design Reading others’ code Observer Observable Composite UML Class Diagrams Sequence Diagrams Package Diagrams X-25
- Slides: 25