Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

32
Lilian Blot Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1

Transcript of Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Page 1: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian BlotLilian Blot

VARIABLE SCOPEEXCEPTIONSFINAL WORD

Final Lecture

Spring 2014TPOP

1

Page 2: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Overview

Variable Scope and Life time

Handling Errors

Java Collections API

Final Words

TPOP

2

Spring 2014

Page 3: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Variable Types

In a class definition, there are three kinds of variables.

instance variables: Any method in the class definition can access these variables

parameter variables: Only the method where the parameter appears can access these variables. This is how information is passed to the object.

local variables: Only the method where the parameter appears can access these variables. These variables are used to store intermediate results.

TPOP

3

Spring 2014

Page 4: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Scope

Related to the idea of ‘block structures’

The scope of a variable (field) is defined as the area where the variable can be seen

‘inner’ blocks can see variables declared in ‘outer’ blocks

TPOP

4

Spring 2014

Page 5: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Scope

TPOP

5

Spring 2014

public class TwoSides{ int side1, side2 ; public boolean testRightTriangle( int hypoteneuse ) { int side1Squared = side1 * side1 ; int side2Squared = side2 * side2 ; int hypSquared = hypoteneuse * hypoteneuse ;

return side1Squared + side2Squared == hypSquared ; }}

Code

Parameter variable

Instance variable

locale variable

Page 6: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Scope

We say the scope of instance variables is the entire class definition. The scope refers to the section of code where a variable can be accessed.

The scope for a parameter is simply the method body in which the parameter is located.

TPOP

6

Spring 2014

Page 7: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Local Variables Have No Memory

When you exit a method, both the local variables and the parameter variables disappear although, if you pass an object as a parameter, you

usually have access to the object when you exit the method.

TPOP

7

Spring 2014

Page 8: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Lifetime

Different kinds of variables have different lifetimes.

Parameter variables exist when the method call is made, and lasts until the method call is complete.

Local variables also have a similar lifetime. They are created when the declaration appears, and lasts until you exit the method.

Instance variables have a much longer lifetime. They are created when the object is constructed, and goes away when the object disappears. The object disappears when it is no longer being used, and when that happens, the

garbage collector gets rid of the object.

The garbage collector is a program that runs when your program runs, and looks for objects with no variables that have handles to it.

TPOP

8

Spring 2014

Page 9: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Scope vs. Lifetime

Scope refers to the range of code where you can access a variable. We can divide scope into method body scope Variable is accessible in method body

only (local variables, parameters) class definition scope Variable is accessible in class definition

(instance variables)Lifetime refers to the amount of time a variable (or

object) exists. We can divide lifetime into categories too: method body lifetime Exists on method body entry,

disappears on method body exit. (local variables, parameters) class definition lifetime Exists as long as object is around

(instance variables)

TPOP

9

Spring 2014

Page 10: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Scope

TPOP

10

Spring 2014

public class TwoSides{ int side1, side2 ; public boolean testRightTriangle( int hypoteneuse ) { if(hypotenuse >= 0){ int side1Squared = side1 * side1 ; int side2Squared = side2 * side2 ; int hypSquared = hypoteneuse * hypoteneuse ; } else: return false;

return side1Squared + side2Squared == hypSquared ; }}

Code

Parameter variable

Instance variable

locale variable

Block scope

ERROR

Page 11: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Be careful

What is the outcome of calling print()?

TPOP

11

Spring 2014

public class TwoSides{ int side1 = 1, side2 = 2; public void print() {

int side1 = 4;System.out.println(side1 * side2);

}}

Code

• The result is 8!• Local variable side1 is hiding instance variable

side1.

Page 12: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian BlotLilian Blot

Handling Errors

Spring 2014TPOP

12

Page 13: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Main concepts to be covered

Defensive programming. Anticipating that things could go wrong.

Exception handling and throwing.

Error reporting.

TPOP

13

Spring 2014

Page 14: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Not always programmer error

Errors often arise from the environment: Incorrect URL entered. Network interruption.

File processing is particular error-prone: Missing files. Lack of appropriate permissions.

TPOP

14

Spring 2014

Page 15: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Error reporting

How to report illegal arguments?

To the user? Is there a human user? Can they solve the problem?

To the client object? Return a diagnostic value. Throw an exception.

TPOP

15

Spring 2014

Page 16: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Client responses

Test the return value. Attempt recovery on error. Avoid program failure.

Ignore the return value. Cannot be prevented. Likely to lead to program failure.

Exceptions are preferable.

TPOP

16

Spring 2014

Page 17: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Throwing an exception

TPOP

17

Spring 2014

/** * Look up a name or phone number and return the * corresponding contact details. * @param key The name or number to be looked up. * @return The details corresponding to the key, * or null if there are none matching. * @throws NullPointerException if the key is null. */public ContactDetails getDetails(String key){ if(key == null) { throw new NullPointerException( "null key in getDetails"); } return book.get(key); }

Code

Page 18: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Throwing an exception

An exception object is constructed: new ExceptionType("...")

The exception object is thrown: throw ...

Javadoc documentation: @throws ExceptionType reason

TPOP

18

Spring 2014

Page 19: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

The exception class hierarchy

TPOP

19

Spring 2014

Page 20: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Exception categories

Checked exceptions Subclass of Exception Use for anticipated failures. Where recovery may be possible.

Unchecked exceptions Subclass of RuntimeException Use for unanticipated failures. Where recovery is unlikely.

TPOP

20

Spring 2014

Page 21: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

The effect of an exception

The throwing method finishes prematurely.

No return value is returned.

Control does not return to the client’s point of call. So the client cannot carry on regardless.

A client may ‘catch’ an exception.

TPOP

21

Spring 2014

Page 22: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Unchecked exceptions

Use of these is ‘unchecked’ by the compiler.

Cause program termination if not caught.

This is the normal practice.

IllegalArgumentException is a typical example.

TPOP

22

Spring 2014

Page 23: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Exception handling

Checked exceptions are meant to be caught.

The compiler ensures that their use is tightly controlled. In both server and client.

Used properly, failures may be recoverable.

TPOP

23

Spring 2014

Page 24: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

The throws clause

Methods throwing a checked exception must include a throws clause:

TPOP

24

Spring 2014

public void saveToFile(String destinationFile) throws IOException{. . .}

Code

Page 25: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

The try statement

Clients catching an exception must protect the call with a try statement:

TPOP

25

Spring 2014

try { Protect one or more statements here.}catch(Exception e) { Report and recover from the exception here.}

Code

Page 26: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Catching multiple exceptions

Clients catching an exception must protect the call with a try statement:

TPOP

26

Spring 2014

try { ... ref.process(); ...}catch(EOFException e) { // Take action on an end-of-file exception. ...}catch(FileNotFoundException e) { // Take action on a file-not-found exception. ...}

Code

Page 27: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

The finally clause

Clients catching an exception must protect the call with a try statement:

TPOP

27

Spring 2014

catch(Exception e) { Report and recover from the exception here.}finally { Perform any actions here common to whether or not an exception is thrown.}catch(FileNotFoundException e) { // Take action on a file-not-found exception. ...}

Code

Page 28: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

The finally clause

A finally clause is executed even if a return statement is executed in the try or catch clauses.

A uncaught or propagated exception still exits via the finally clause.

TPOP

28

Spring 2014

Page 29: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Defining new exceptions

Extend RuntimeException for an unchecked or Exception for a checked exception.

Define new types to give better diagnostic information. Include reporting and/or recovery information.

TPOP

29

Spring 2014

Page 30: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Defining new exceptions

TPOP

30

Spring 2014

public class NoMatchingDetailsException extends Exception{ private String key;

public NoMatchingDetailsException(String key) { this.key = key; }  public String getKey() { return key; } public String toString() { return "No details matching '" + key + "' were found."; }}

Code

Page 31: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Summary

Runtime errors arise for many reasons. An inappropriate client call to a server object. A server unable to fulfill a request. Programming error in client and/or server.

Runtime errors often lead to program failure.

Defensive programming anticipates errors – in both client and server.

Exceptions provide a reporting and recovery mechanism.

TPOP

31

Spring 2014

Page 32: Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.

Lilian Blot

Final Words

TPOP

32

Spring 2014