Download presentation
Presentation is loading. Please wait.
1
Administrivia Midterm exam: Mar 10 (in class) Interfaces vs. Abstract classes Inner classes Data views; iterators Lexical analyzers (tokenizers) Theory: Bayesian spam analysis A*, admissibility, monotonicity, etc. Tools: Javadoc CVS Etc...
2
Definition of the Day... crock :n. [from the American scatologism crock of s***] 1. An awkward feature or programming technique that ought to be made cleaner. 2. A technique that works acceptably, but which is quite prone to failure if disturbed in the least. The Jargon File, v. 4.7.7, Mar 1, 2003
3
Exceptions, Errors, Assertions, and all that...
4
Expecting the Unexpected Some huge fraction (30%? 50%?) of code is handling unexpected cases. Problem is that code that detects unexpected circumstance doesn’t always know what to do about it. Idea of Exceptions, et al. is to move handling of errors out to appropriate place to deal with them Nice idea in principle; very hard to get right in practice... :-P
5
Ideal Model... Throw + try/catch/finally public int fooMethod(int a) { if (a<0) { throw new IllegalArgumentException(“a must “ + “be non-negative, not a=“ + a); } // etc... } public void barMethod() { try { fooMethod(-37); } catch (IllegalArgumentException e) { // do something about it... }
6
Nastier in Practice... Distinction between “checked” and “unchecked” exceptions “Checked” == compiler checks to make sure you catch (or explicitly allow to pass through) an exception/family of exceptions “Unchecked” don’t need to be declared (e.g., IllegalArgumentException ) public void myLoader(String fname) throws IOException { FileReader in=new FileReader(fname); // do stuff to in... in.close(); }
7
What’s the “Real” Difference? How does the compiler know which is which?
8
What’s the “Real” Difference? How does the compiler know which is which? Compiler doesn’t force checks for two families of exceptions: Error and its subclasses RuntimeException and its subclasses Object Throwable ErrorException RuntimeException
9
When to Use Them So you could make an unchecked exception by extending Error or RuntimeException But do you want to? Problem is that checked exceptions tell you a lot about how a class/interface/type works E.g., java.io methods mostly throw checked exceptions Tells you what kind of failure modes they have Want to use checked exceptions whenever you (practically) can
10
When is it Practical? Some books tell you “Always used checked exceptions.” Wrong.
11
When is it Practical? Checked exceptions are good when the receiving code can actually do something about the problem IOExceptions Can’t open file => ask user for new file name File ends prematurely => close file, discard loaded data, ask for new file, etc. PrintException Printer out of paper => tell user to go fix paper and continue ParseException Unexpected/missing token => warn user
12
So What About RuntimeException ? Better for things that code can’t do much about Programming errors Precondition errors ( if (a<0) { throw... } ) Stuff that may or may not be b/c of structure of code (e.g., may be related to user input) Sometimes still useful to put in throws clause Always useful to document in API docs (javadoc) Your book says: “Never extend RuntimeException ” That’s wrong. But do be careful. Not an excuse to avoid throws clause!
13
Errors java.lang.Error is usually used to indicate a problem in the Java interpreter (JVM) Mostly stuff that’ll cause your program to die a hideous, painful, agonizing death anyway Class loader problems Bugs in the JVM (!) Circular code definitions (that sneak through compiler!) Out of memory Very rare that your code will need to generate one of these itself Mostly, do what you need w/ (Runtime)Exception
14
Assertions Assert provides a “conditional” exception Can turn on or off all assertion checks in code Mostly good for debugging Should be used for fundamental design problems in the code Stuff that should never happen E.g. public static void doit(int a) { switch a { case 0: doCase0(); break; case 1: doCase1(); break; default: assert false : “a=“ + a; }
15
Assertions, cont’d assert is only introduced in java 1.4+ Not in your book :-P Have to compile w/ “-source 1.4” switch When running, can turn on or off assertions java foo => assertions disabled java -ea foo => assertions enabled Can have same code work differently in “production” vs “debug” mode Good for guarding against deep logic errors “This should never happen” sorts of things
16
Do’s Use checked exceptions when you possibly can Provide useful messages to your exceptions Provide erroneous data when you can (helpful in debugging) IllegalArgumentException(“a should be >0”); IllegalArgumentException(“a should be >0; not a=“ + a); Use RuntimeExceptions for argument validation But document them anyway!
17
Don’t’s throw new Exception(“my message”) Extend Throwable (no need) Use exceptions for “normal” control flow Eeeeeeeeeeeeeevil! (Why?) int i=0; int[] a=new int[10]; try { while (true) { doSomething(a[i++]); } catch (ArrayIndexOutOfBoundsException e) {}
18
Chaining Exceptions Also new in Java 1.4+ Sometimes, you get an exception that doesn’t match your contract E.g., method guarantees to throw only NoSuchElementException, but gets an EOFException internally Want to “re-throw” the exception “wrapped” in the correct exception class Use the initCause() and getCause() methods Sometimes have constructors for chaining Can chain arbitrarily far
19
Finally, finally finally clause prevents code being “missed” by thrown exceptions throw seems to “skip” intervening code until appropriate “catch” is found Not quite right -- locally allocated objects are deallocated Any “finally” blocks are executed Use finally to be sure that certain code is executed, even if rest of code is missed by exceptions Good for non-Java resources you may have open (e.g., files, network or DB connections, etc.)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.