1CMSC 132: Object-Oriented Programming IIExceptions & Effective JavaDepartment of Computer ScienceUniversity of Maryland, College Park2OverviewExceptionsMotivationRepresentation in JavaEffective Java3Exception HandlingPerforming action in response to exceptionExample actionsIgnore exceptionPrint error messageRequest new dataRetry actionApproaches1.Exit program2.Exit method returning error code3.Throw exception4ProblemMay not be able to handle error locallyNot enough information in method / classNeed more information to decide actionHandle exception in calling function(s) insteadDecide at application level (instead of library)ExamplesIncorrect data format ⇒⇒⇒⇒ask user to reenter data Unable to open file ⇒⇒⇒⇒ask user for new filenameInsufficient disk space ⇒⇒⇒⇒ask user to delete filesWill need to propagate exception to caller(s)5Exception Handling – Exit ProgramApproachExit program with error message / error codeExampleif (error) {System.err.println(“Error found”); // messageSystem.exit(1); // error code}ProblemDrastic solutionEvent must be handled by user invoking programProgram may be able to deal with some exceptions6Exception Handling – Error CodeApproachExit function with return value ⇒⇒⇒⇒error codeExampleA( ) { if (error) return (-1); }B( ) { if ((retval = A( )) == -1) return (-1); }ProblemsCalling function must check & process error codeMay forget to handle error codeMay need to return error code to callerAgreement needed on meaning of error codeError handling code mixed with normal code7Exception Handling – Throw ExceptionApproachThrow exception (caught in parent’s catch block)ExampleA( ) { if (error) throw new ExceptionType(); }B( ) { try { A( ); } catch (ExceptionType e) { ...action... } }Java exception backtracks to caller(s) until matching catch block found8Exception Handling – Throw ExceptionAdvantagesCompiler ensures exceptions are caught eventuallyNo need to explicitly propagate exception to callerBacktrack to caller(s) automaticallyClass hierarchy defines meaning of exceptionsNo need for separate definition of error codesException handling code separate & clearly marked9Representing ExceptionsExceptions represented asObjects derived from class ThrowableCodepublic class Throwable( ) extends Object {Throwable( ) // No error messageThrowable( String mesg ) // Error messageString getMessage() // Return error mesgvoid printStackTrace( ) { … } // Record methods… // called & location}10Representing ExceptionsJava Exception class hierarchyTwo types of exceptions ⇒⇒⇒⇒checked & unchecked11ObjectObjectErrorErrorThrowableThrowableExceptionExceptionLinkageErrorLinkageErrorVirtualMachoneErrorVirtualMachoneErrorClassNotFoundExceptionClassNotFoundExceptionCloneNotSupportedExceptionCloneNotSupportedExceptionIOExceptionIOExceptionAWTErrorAWTError…AWTExceptionAWTExceptionRuntimeExceptionRuntimeException…ArithmeticExceptionArithmeticExceptionNullPointerExceptionNullPointerExceptionIndexOutOfBoundsExceptionIndexOutOfBoundsExceptionUncheckedUncheckedCheckedCheckedNoSuchElementExceptionNoSuchElementException…Representing ExceptionsJava Exception class hierarchy12Unchecked ExceptionsClass Error & RunTimeExceptionSerious errors not handled by typical programUsually indicate logic errorsExampleNullPointerException, IndexOutOfBoundsExceptionCatching unchecked exceptions is optionalHandled by Java Virtual Machine if not caught13Checked ExceptionsClass Exception (except RunTimeException)Errors typical program should handleUsed for operations prone to errorExampleIOException, ClassNotFoundExceptionCompiler requires “catch or declare”Catch and handle exception in method, ORDeclare method can throw exception, force calling function to catch or declare exception in turnExamplevoid A( ) throws ExceptionType { … }14Designing & Using ExceptionsUse exceptions only for rare eventsNot for common cases ⇒⇒⇒⇒checking end of loopHigh overhead to perform catchPlace statements that jointly accomplish task into single try / catch blockUse existing Java Exceptions if possible15Designing & Using ExceptionsAvoid simply catching & ignoring exceptionsPoor software development styleExampletry {throw new ExceptionType1( );throw new ExceptionType2( );throw new ExceptionType3( );}catch (Exception e) { // catches all exceptions… // ignores exception & returns}16OverviewExceptionsEffective JavaPuzzlersPrinciples17Effective JavaTitleEffective Java Programming Language GuideAuthorJoshua BlochContentsUseful tips for Java programming18Java Puzzlers (By J. Bloch)JavaSimple and elegantNeed to avoid some sharp corners!PuzzlersJava code fragmentsExpose some tricky aspects of JavaEffective JavaWays of avoiding Java programming problems19What's In A Name?public class Name {private String myName;public Name(String n) { myName = n; }public boolean equals(Object o) {if (!(o instanceof Name)) return false;Name n = (Name)o;return myName.equals(n.myName);}public static void main(String[ ] args) {Set s = new HashSet();s.add(new Name("Donald"));System.out.println(s.contains(new Name("Donald")));} }Output1. True2. False3. It VariesName class violates Java hashCode( ) contract.If you override equals( ), must also override hashCode( )!20You're Such A Characterpublic class Trivial {public static void main(String args[ ]) {System.out.print("H" + "a");System.out.print('H' + 'a');}}Output1. Ha2. HaHa3. NeitherPrints Ha169'H' + 'a' evaluated as int, then converted to String!Use string concatenation (+) with care. At least one operand must be a String21The Confusing Constructorpublic class Confusing {public Confusing(Object o) {System.out.println("Object");}public Confusing(double[] dArray) {System.out.println("double array");}public static void main(String args[]) {new Confusing(null);}}Output1. Object2. double array3. NeitherWhen multiple overloadings apply,the most specific winsAvoid overloading.If you overload, avoid ambiguity22Time For A ChangeProblemIf you pay $2.00 for a gasket that costs $1.10, how much change do you get?public class Change {public static void main(String args[ ]) {System.out.println(2.00 - 1.10);}}Output1. 0.92. 0.903. NeitherPrints 0.8999999999999999. Decimal values can’t be represented exactly by float or doubleAvoid float or double where exact answers are required. Use BigDecimal, int, or long instead23A Private Matterclass Base {public String name = "Base";}class Derived extends Base {private String name = "Derived";}public class
View Full Document