07ExceptionsAndMutabilitySmall

07ExceptionsAndMutabilitySmall - Lecture Set #7: Exceptions...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
1 CMSC 131Fal 2009 Jan Plane (adapted from Bonnie Dorr) Lecture Set #7: Exceptions 1. Break and Continue for Loops 2. Exceptions 3. Mutability/Immutability 4. Stringbuffer class CMSC 131 Fal 2009 Jan Plane (adapted from Bonnie Dorr) 1 break from loops c break can also be used to exit immediately from any loop c while c do-while c for c 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>; } c Loop only terminates when break executed c This only happens when n < 0 CMSC 131 Fal 2009 Jan Plane (adapted from Bonnie Dorr) 2 Warning about break c Undisciplined use of break can make loops impossible to understand c Termination of loops without break can be understood purely by looking while , for parts c When break included, arbitrary termination behavior can be introduced c Rule of thumb: use break only when loop condition is always true (i.e. break is only way to terminate loop) c When you use it, make sure it has a good comment explaining what is happening
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 CMSC 131 Fal 2009 Jan Plane (adapted from Bonnie Dorr) 3 continue Statement c continue can also be used to affect loops c break halts loops c continue jumps to bottom of loop body c Following prints even numbers between 0 and 10 for (int i = 0; i <= 10; i++){ if (i % 2 == 1) continue; System.out.println (i); } c Effect of continue statement is to jump to bottom of loop immediately when i is odd c This bypasses println! c continue should be avoided c Confusing c Easy equivalents exist (e.g. if-else ) c Included in Java mainly for historical reasons c When you use it, make sure it has a good comment explaining what is happening CMSC 131Fal 2009 Jan Plane (adapted from Bonnie Dorr) 4 Exceptions c Programs can generate errors c Arithmetic Divide by zero, overflows, … c Object / Array Using a null reference, illegal array index, … c 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), … c Application-specific Errors particular to application (e.g., attempt to remove a nonexistent
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 6

07ExceptionsAndMutabilitySmall - Lecture Set #7: Exceptions...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online