Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS102 – Exceptions David Davenport Latest: May 2015

Similar presentations


Presentation on theme: "CS102 – Exceptions David Davenport Latest: May 2015"— Presentation transcript:

1 CS102 – Exceptions David Davenport Latest: May 2015
Previous: May 2013, Spring 2002 See ExceptionPlay.java

2 Exceptions Handling run-time errors/problems
check for and handle eg. Avoid divide by zero by testing denominator use exceptions consistent form uncluttered code compiler can help but maybe slower The OOP way!

3 Exception Class Hierarchy
LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException ArrayIndexOutOfBoundsException several more classes All exceptions/errors are run-time! RunTimeExceptions are not checked by the compiler so programmer is not required to acknowledge them All other types require programmers to write code acknowledging a problem before the program will compile! RuntimeExceptions are unchecked Seriously bad news!

4 Exception Handling... Exceptions not handled in a method are passed up to calling method If not handled (caught) anywhere then program prints error message and, if console program, stops! (but GUI programs don’t...) … too hot to handle cartoon … (passing hot potato) Oven gloves & hot potatoes!

5 Can specify multiple catch clauses to handle different exception types
Handling Exceptions Either “pass-the-buck” or handle them public void myMethod() throws ExceptionType { statements; } Unchecked exceptions don’t require attention, but can be caught & handled if desired. try { statements; } catch (ExceptionType e) { // handler for exception finally { // statements always done “throws” - pass the buck… handling the exception is someone else’s responsibility! - can list multiple exception types separated by commas. Any statements in the try part that follow the one that causes an exception are not done. (Optional) One or more catch clauses must list most specific catch clauses first since Java does the first matching one only. (Optional) finally clause… seems irrelevant, but may not be if the catch clauses themselves can cause an exception! Note: newer versions of Java, e.g. 1.7+, allow multiple exception types to be listed in catch clause, eg. catch ( IOException | SQLException ex) { … } allow try with resources, which are automatically closed afterwards “The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.” Can specify multiple catch clauses to handle different exception types Optional clause

6 Examples... Divide by zero try { System.out.println( 25/0); }
catch (Exception e) { System.out.println( e); System.out.println( “wow..”); Stack calculator (see data structures...) In Stack class... public int pop() { if ( isEmpty() ) throw new StackUnderFlowException(); else return ...; } What happens if you change the exception type to ArithmeticException or InputMismatchException? What happens if you change add another catch clause for ArithmeticException –before/after this one?

7 Exceptions are relatively slow!
Throwing Exceptions When error occurs simply throw a new exception Create your own Exception Types Exceptions are relatively slow! if ( x != y ) throw new MyExceptionType( “oops!” ); Can catch one type of exception and throw another. If ( n < 0) throw new IllegalArgumentException( “n must be positive”); Note: extend RunTimeException if programmmer not required to write code when using it! public class MyExceptionType extends Exception { public MyExceptionType( String message) { super( message); }

8 Files & Exception handling
String filename; DataInputStream fin = null; try { System.out.print( "Enter filename: "); filename = scan.readLine(); fin = new DataInputStream( new FileInputStream( filename) ); while (true) { int i = fin.readByte(); System.out.print( i + "|" + (char) i + "| " ); } } catch ( FileNotFoundException e) { System.out.println( e + "\n--- Sorry, can't find a file with that name!" ); } catch ( IOException e ) { System.out.println( e + "\n--- The entire file has been processed!" ); fin.close(); } finally { System.out.println( "--- all done.."); Even though end of file is not exactly an exceptional circumstance, many languages, including Java, allow eof processing using exceptions. Note: readLine() in ??? class is the one “exception” to the rule; it doesn’t generate an exception (it returns null instead)!


Download ppt "CS102 – Exceptions David Davenport Latest: May 2015"

Similar presentations


Ads by Google