DOC PREVIEW
UMD CMSC 132 - Program Correctness, Exceptions

This preview shows page 1-2-3-18-19-37-38-39 out of 39 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 39 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 39 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 39 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 39 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 39 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 39 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 39 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 39 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 39 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

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

UMD CMSC 132 - Program Correctness, Exceptions

Documents in this Course
Notes

Notes

8 pages

Recursion

Recursion

12 pages

Sorting

Sorting

31 pages

HTML

HTML

7 pages

Trees

Trees

19 pages

HTML

HTML

18 pages

Trees

Trees

19 pages

Honors

Honors

19 pages

Lecture 1

Lecture 1

11 pages

Quiz #3

Quiz #3

2 pages

Hashing

Hashing

21 pages

Load more
Download Program Correctness, Exceptions
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Program Correctness, Exceptions and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Program Correctness, Exceptions 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?