DOC PREVIEW
UMD CMSC 131 - Lecture Set #7: Exceptions & Mutability Issues

This preview shows page 1-2 out of 6 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 6 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 6 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 6 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Lecture Set 7 Exceptions Mutability Issues 1 2 3 4 Break and Continue for Loops Exceptions Mutability Immutability StringBuffer class CMSC 131Fall 2009 Jan Plane adapted from Bonnie Dorr break from loops break can also be used to exit immediately from any loop while do while for e g Read numbers from input until negative number encountered Scanner sc new Scanner System in int n while true n sc nextInt if n 0 break else process n Loop only terminates when break executed This only happens when n 0 breaks past if statements Always breaks to first enclosing loop 1 CMSC 131 Fall 2009 Jan Plane adapted from Bonnie Dorr Warning about break Undisciplined use of break can make loops impossible to understand Termination of loops without break can be understood purely by looking while for parts When break included arbitrary termination behavior can be introduced Rule of thumb use break only when loop condition is always true i e break is only way to terminate loop When you use it make sure it has a good comment explaining what is happening CMSC 131 Fall 2009 Jan Plane adapted from Bonnie Dorr 2 1 continue Statement continue can also be used to affect loops Following prints even numbers between 0 and 10 break halts loops continue jumps to bottom of loop body for int i 0 i 10 i if i 2 1 continue System out println i continue should be avoided Effect of continue statement is to jump to bottom of loop immediately when i is odd This bypasses println Confusing Easy equivalents exist e g if else Included in Java mainly for historical reasons When you use it make sure it has a good comment explaining what is CMSC 131 Fall 2009 happening Jan Plane adapted from Bonnie Dorr 3 Exceptions Programs can generate errors Arithmetic Divide by zero overflows Object Array Using a null reference illegal array index File and I O Nonexistent file attempt to read past the end of the file we ll see more about file I O later in course Application specific Errors particular to application e g attempt to remove a nonexistent customer from a database 1 2 3 4 In Java something that is outside the norm exception What to do when an error occurs Basically ignore it Print an error message and terminate Have the method handle it internally Handle error in the code where the problem lies as best you can Have the method pass it off to someone else to handle Return error code so that whoever called this function can handle it Modern language approach Cause exception to be thrown and caught or processed by any function up the stack trace CMSC 131Fall 2009 Jan Plane adapted from Bonnie Dorr 4 Exception Behavior If program generates throws exception then default behavior is Java clobbers aborts the program Stack trace is printed showing where exception was generated red and blue in Eclipse window Example public int mpg int miles int gallons return miles gallons Throws an exception and terminates the program CMSC 131Fall 2009 Jan Plane adapted from Bonnie Dorr 5 2 Throwing Exceptions Yourself To throw an exception use throw command throw e e must evaluate to an exception object You can create exceptions just like other objects e g RuntimeException e new RuntimeException Uh oh RuntimeException is a class Calling new this way invokes constructor for this class RuntimeException generalizes other kinds of exceptions e g ArithmeticException CMSC 131Fall 2009 Jan Plane adapted from Bonnie Dorr 6 Exceptions Classes and Types Exceptions are objects Some examples from the Java class library mostly java lang ArithmeticException Used e g for divide by zero NullPointerException attempt to access an object with a null reference IndexOutOfBoundsException array or string index out of range ArrayStoreException attempting to store wrong type of object in array EmptyStackException attempt to pop an empty Stack java util IOException attempt to perform an illegal input output operation java io NumberFormatException attempt to convert an invalid string into a number e g when calling Integer parseInt RuntimeException general run time error subsumes above Exception The most generic type of exception CMSC 131Fall 2009 Jan Plane adapted from Bonnie Dorr 7 Throw Example public int mpg int miles int gallons if gallons 0 throw new NullPointerException else return miles gallons CMSC 131Fall 2009 Jan Plane adapted from Bonnie Dorr 8 3 Java Exceptions in Detail Exceptions are special objects in Java They are created from classes The classes are derived inherit from a special class Throwable We will learn more about inheritance etc later Every exception object class has Exception String message Constructor taking an explanation as an argument String getMessage Method returning the embedded message of the exception void printStackTrace Method printing the call stack when the exception was thrown CMSC 131Fall 2009 Jan Plane adapted from Bonnie Dorr 9 Handling Exceptions Aborting program not always a good idea E mail can t lose messages E commerce must ensure correct handling of private info in case of crash Antilock braking air traffic control must recover and keep working Java provides the programmer with mechanisms for recovering from exceptions CMSC 131Fall 2009 Jan Plane adapted from Bonnie Dorr 10 Java Exception Terminology When an anomaly is detected during program execution the JVM throws a particular type of exception There are built in exceptions Users can also define their own more later To avoid crashing a program can catch a thrown exception if it isn t caught you see the red and blue messages stack trace An exception generated by a piece of code can only be caught if the program is alerted This process is called trying the piece of code CMSC 131Fall 2009 Jan Plane adapted from Bonnie Dorr 11 4 Catch Example try System out println Start mpg 5 0 System out println Finish catch Exception e System out println e e CMSC 131Fall 2009 Jan Plane adapted from Bonnie Dorr 12 Exception Propagation In previous example Exception thrown in one method but caught in another Java uses exception propagation to look for exception handlers When an exception occurs Java pops back up the call stack to each of the calling methods to see whether the exception is being handled by a try catch block This is exception propagation The first method it finds that catches the exception will have its catch block executed Execution resumes normally in the method after this catch block If we get all the way back to main and no method catches this exception Java catches it and aborts


View Full Document

UMD CMSC 131 - Lecture Set #7: Exceptions & Mutability Issues

Documents in this Course
Set #3

Set #3

7 pages

Exam #1

Exam #1

6 pages

Exam #1

Exam #1

6 pages

Notes

Notes

124 pages

Notes

Notes

124 pages

Load more
Download Lecture Set #7: Exceptions & Mutability Issues
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 Lecture Set #7: Exceptions & Mutability Issues 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 Lecture Set #7: Exceptions & Mutability Issues 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?