CMSC 132: Object-Oriented Programming IIProgram Correctness, ExceptionsDepartment of Computer ScienceUniversity of Maryland, College ParkOverviewProgram correctness is determined by the presence / absence of program defects (errors)IssuesTypes of errorsTestingDebuggingExceptionsProgram ErrorsTypes of errorsCompile-time (syntax) errorsRun-time errorsLogic errorsProgram Errors – Compile TimeCompile-time (syntax) errorsErrors in code constructionLexical (typographical), grammatical, typesDetected during compilationUsually easy to correct quicklyExamplesMisspelled keywordMissing or misplaced symbolIncorrect operator for variable typeProgram Errors – Run TimeRun-time errorsOperations illegal / impossible to executeDetected during program executionBut not detectable at compile timeTreated as exceptions in JavaExampleDivision by zeroArray index out of boundsUsing null pointerIllegal format conversionProgram Errors – LogicLogic errorsOperations leading to incorrect program stateMay (or may not) lead to run-time errorsProblem in design or implementation of algorithmExamplesComputing incorrect arithmetic valueIgnoring illegal inputHardest error to handleDetect by testingFix by debuggingTestingRun program (or part of program) under controlled conditions to verify behaviorDetects run-time error if exception thrownDetects logic error if behavior is incorrectIssuesSelecting test casesTesting different parts of programVisibility of program codeTest coverage…Test CoverageTest coverageWhether code is executed by some test caseAutomatically calculated by submit server For set of tests selected (from link)E.g., student tests, public tests, student+public testsFor conditionals, reports X/Y whereX = # tests executing TrueY = # tests executing FalseColorGreen = executed by some test casePink = not executedTest Coverage ExampleDebuggingProcess of finding and fixing software errorsAfter testing detects errorGoalDetermine cause of run-time & logic errorsCorrect errors (without introducing new errors)Similar to detective workCarefully inspect information in programCodeValues of variablesProgram behaviorDebugging – ApproachesClassicInsert debugging statementsTrace program control flowDisplay value of variablesModernIDE (integrated development environment)Interactive debuggerInteractive DebuggerCapabilitiesProvides trace of program executionShows location in code where error encounteredInteractive program executionSingle step through codeRun to breakpointsDisplays values of variablesFor current state of programInteractive DebuggerSingle stepExecute single line of code at a timeWhen executing method, canFinish entire methodExecute first line in methodTedious (or impractical) for long-running programsBreakpointSpecify location(s) in codeExecute program until breakpoint encounteredCan skip past uninteresting codeEclipse DebuggerBreakpointSingle StepData DisplayExceptionsRare event outside normal behavior of codeUsually a run-time errorExamplesDivision by zeroAccess past end of arrayOut of memoryNumber input in wrong format (float vs. integer)Unable to write output to fileMissing input fileException HandlingPerforming action in response to exceptionExample actionsIgnore exceptionPrint error messageRequest new dataRetry actionApproaches1. Exit program2. Exit method returning error code3. Throw exceptionProblemMay 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)Exception 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 exceptionsException 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 codeException Handling – Throw ExceptionApproachThrow exceptionExampleA( ) { if (error) throw new ExceptionType(); }B( ) { try { A( ); } catch (ExceptionType e) { ...action... } }Java exception backtracks to caller(s) until matching catch block foundException 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 markedRepresenting Exceptions in JavaExceptions 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}Representing ExceptionsJava Exception class hierarchyTwo types of exceptions checked & uncheckedObjectErrorThrowableExceptionLinkageErrorVirtualMachoneErrorClassNotFoundExceptionCloneNotSupportedExceptionIOExceptionAWTError…AWTExceptionRuntimeException…ArithmeticExceptionNullPointerExceptionIndexOutOfBoundsExceptionUncheckedCheckedNoSuchElementException…Representing ExceptionsJava Exception class hierarchyUnchecked ExceptionsClass Error & RunTimeExceptionSerious errors not handled by typical programUsually indicate logic errorsExampleNullPointerException, IndexOutOfBoundsExceptionCatching unchecked exceptions is optionalHandled by Java Virtual Machine if not caughtChecked 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 { … }Generating & Handling ExceptionsJava primitivesTryThrowCatchFinallyProcedure for
View Full Document