Handling errors Exception handling and throwing Simple file processing.

47
Handling errors Exception handling and throwing Simple file processing

Transcript of Handling errors Exception handling and throwing Simple file processing.

Page 1: Handling errors Exception handling and throwing Simple file processing.

Handling errors

Exception handling and throwing

Simple file processing

Page 2: Handling errors Exception handling and throwing Simple file processing.

Outline

• Error example• Defensive Programming

• Throwing Exception

• Catching Exception

• Defining new Exception Types– Checked vs unchecked

Page 3: Handling errors Exception handling and throwing Simple file processing.

Error situations

• Programmer errors– Incorrect implementation– Inappropriate object request

• Errors often arise from the environment:– incorrect URL entered– network interruption

• File processing is particularly error prone:– missing files– lack of appropriate permissions

Page 4: Handling errors Exception handling and throwing Simple file processing.

Example: Runtime error

• Use:AddressBook friends = new AddressBook(); friends.removeDetails("frederik");

• Result:java.lang.NullPointerException

at AddressBook.removeDetails(AddressBook.java:119) ...

• In class AddressBook:public void removeDetails(String key) { ContactDetails details = (ContactDetails) book.get(key); book.remove(details.getName()); ...}

1. returns null when key

does not exist in book2. trying to call method on null

results in exception

Page 5: Handling errors Exception handling and throwing Simple file processing.

Outline

• Error example

• Defensive Programming• Throwing Exception

• Catching Exception

• Defining new Exception Types– Checked vs unchecked

Page 6: Handling errors Exception handling and throwing Simple file processing.

Defensive programming

• Defensive programming in client-server interaction– server assumes that clients are not well

behaved (and potentially hostile)– E.g. server checks arguments to constructors

and methods

• Significant overhead in implementation

Page 7: Handling errors Exception handling and throwing Simple file processing.

Defensive programming

• Modified method in class AddressBook:

public void removeDetails(String key) {

if(keyInUse(key)) {

ContactDetails details =

(ContactDetails) book.get(key);

book.remove(details.getName());

book.remove(details.getPhone());

numberOfEntries--;

}

}

check argument

Page 8: Handling errors Exception handling and throwing Simple file processing.

Server 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

Page 9: Handling errors Exception handling and throwing Simple file processing.

Returning a diagnostic

public boolean removeDetails(String key) { if(keyInUse(key)) { ContactDetails details = (ContactDetails) book.get(key); book.remove(details.getName()); book.remove(details.getPhone()); numberOfEntries--; return true; } else { return false; }}

did any errors arise?

Page 10: Handling errors Exception handling and throwing Simple file processing.

QUIZWhich of the three

remove methods use appropriate defensive programming?

1. none

2. A

3. B

4. C

5. A, B

6. A, C

7. B, C

8. All three

private class Dictionary {

List<String> list = new ArrayList<String>();

public void add(String w) { list.add(w); }

public boolean removeA(String w) {

list.remove(list.indexOf(w));

return true;

}

public boolean removeB(String w) {

if (list.size()==0) return false;

else return removeA(w);

}

public boolean removeC(String w) {

if (!list.contains(w)) return false;

else return removeA(w);

}

}

Page 11: Handling errors Exception handling and throwing Simple file processing.

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

Page 12: Handling errors Exception handling and throwing Simple file processing.

Outline

• Error example

• Defensive Programming

• Throwing Exception• Catching Exception

• Defining new Exception Types– Checked vs unchecked

Page 13: Handling errors Exception handling and throwing Simple file processing.

Exception-throwing principles

• A special language feature

• No special return value needed

• Errors cannot be ignored in the client– The normal flow-of-control is interrupted

• Specific recovery actions are encouraged

Page 14: Handling errors Exception handling and throwing Simple file processing.

Throwing an Exceptionpublic ContactDetails getDetails(String key) { if (key==null) { throw new IllegalArgumentException(

"null key in getDetails"); } return (ContactDetails) book.get(key);}

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

• The exception object is thrown:– throw ...

Page 15: Handling errors Exception handling and throwing Simple file processing.

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

Page 16: Handling errors Exception handling and throwing Simple file processing.

Outline

• Error example

• Defensive Programming

• Throwing Exception

• Catching Exception• Defining new Exception Types

– Checked vs unchecked

Page 17: Handling errors Exception handling and throwing Simple file processing.

The try block

• Clients catching an exception must protect the call with a try block

try {

Protect one or more statements here.

} catch(Exception e) {

Report and recover from the exception here

}

Page 18: Handling errors Exception handling and throwing Simple file processing.

The try block

try { addressbook.saveToFile(filename); tryAgain = false;} catch(IOException e) { System.out.println("Unable to save to " + filename); tryAgain = true;}

exception thrown from here

control transfers to here

Page 19: Handling errors Exception handling and throwing Simple file processing.

Catching multiple exceptions

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. ...}

Page 20: Handling errors Exception handling and throwing Simple file processing.

The finally clause

try { Protect one or more statements here.} catch(Exception e) { Report and recover from the exception here.} finally { Perform any actions here common to whether or not an exception is thrown.}

Page 21: Handling errors Exception handling and throwing Simple file processing.

The finally clause

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

• An uncaught or propagated exception still exits via the finally clause

Page 22: Handling errors Exception handling and throwing Simple file processing.

QUIZWhich statement is

executed immediately after the throw statement?

1. Line A

2. Line B

3. Line C

4. Line D

5. Program stops with exception failure

6. None of 1-5

public static void main(String[] args) {

int arg = 0;

double inv = inverse(arg);

System.out.println(arg);

}

private static double inverse(int n) {

double result=0;

try {

if (n==0)

throw new IllegalArgumentException(

"cannot take inverse of 0");

result = 1.0/n;

} catch (IllegalArgumentException e) {

e.printStackTrace();

} finally {

return result;

}

}

A

B

C

D

Page 23: Handling errors Exception handling and throwing Simple file processing.

Outline

• Error example

• Defensive Programming

• Throwing Exception

• Catching Exception

• Defining new Exception Types– Checked vs unchecked

Page 24: Handling errors Exception handling and throwing Simple file processing.

Defining new exceptions

• Extend Exception or RuntimeException

• Define new types to give better diagnostic information– include reporting and/recovery information

Page 25: Handling errors Exception handling and throwing Simple file processing.

The exception class hierarchy

Page 26: Handling errors Exception handling and throwing Simple file processing.

Exception categories

• Checked exception– subclass of Exception– use for anticipated failures – where recovery may be possible

• Unchecked exception– subclass of RuntimeException– use for unanticipated failures– where recovery is unlikely

Page 27: Handling errors Exception handling and throwing Simple file processing.

Unchecked exceptions

• Use of these is 'unchecked' by the compiler

• Cause program termination if not caught– this is normal practice– NullPointerException is a typical

example

Page 28: Handling errors Exception handling and throwing Simple file processing.

Checked exceptions

• 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

Page 29: Handling errors Exception handling and throwing Simple file processing.

The throws clause

• Methods throwing a checked exception must include a throws clause:

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

Page 30: Handling errors Exception handling and throwing Simple file processing.

Example: new checked exception

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."; }}

Page 31: Handling errors Exception handling and throwing Simple file processing.

QUIZAny compiler errors ?

1. No compiler errors

2. Method A: needs ”throws” in header

3. Method A: needs ”try-catch” in body

4. Method B: needs ”throws” in header

5. Method main: needs ”throws” in header

6. Both 2 and 4

7. Both 4 and 5

8. Both 2, 4 and 5

9. Other errors

public class Quiz3 {

private static class MyException

extends Exception {}

private static void B() {

throw new MyException();

}

private static void A() {

B();

}

public static void main(String[] args) {

try {

A();

} catch (MyException e) {

e.printStackTrace();

}

}

}

Page 32: Handling errors Exception handling and throwing Simple file processing.

QUIZWhat is the difference between checked and unchecked exceptions?

1. Unchecked exceptions may print any kind of message, whereas checked ones must print a programmer defined message

2. Unchecked exceptions must be handled with a programmed try/catch block, and checked exceptions with a try/catch/finally block

3. Unchecked exceptions need not be handled, but checked exceptions must be handled with a try/catch block

4. Checked exceptions must be handled with a programmed try/catch block, and unchecked exceptions with a try/catch/finally block

5. Checked exceptions need not be handled, but unchecked exceptions must be handled with a try/catch block

6. There is no formal difference between checked and unchecked exceptions

Page 33: Handling errors Exception handling and throwing Simple file processing.

Outline

• Input/output• Text files

• Terminal / keyboard

• Binary Files

Page 34: Handling errors Exception handling and throwing Simple file processing.

Input-output

• Input-output is particularly error-prone– it involves interaction with the external

environment

• java.io.IOException is a checked exception

Page 35: Handling errors Exception handling and throwing Simple file processing.

Two ways to store data

• Text format– *.txt, *.java, *.xml– human-readable form– Sequence of characters

• integer 12345 stored as 49 50 51 52 53 (ascii for "1" "2" "3" "4" "5“)

– use Reader and Writer (and their subclasses)(based on char type)

• Binary format– *.doc, *.class, *.pdf– more compact and efficient

• integer 12345 stored as 00 00 48 57 (12345 = 48*256+57)

– Use InputStream and OutputStream (and their subclasses)(based on byte type)

Page 36: Handling errors Exception handling and throwing Simple file processing.

Outline

• Input/output

• Text files• Terminal / keyboard

• Binary Files

Page 37: Handling errors Exception handling and throwing Simple file processing.

Text output

• Use the FileWriter class– open a file– write to the file– close the file

• Failure at any point results in an IOException.

Page 38: Handling errors Exception handling and throwing Simple file processing.

Text outputtry { FileWriter writer = new FileWriter("name of file"); while(there is more text to write) { ... writer.write(next piece of text); ... } writer.close();} catch(IOException e) { something went wrong with accessing the file}

Page 39: Handling errors Exception handling and throwing Simple file processing.

QUIZWhich statements need to go in a try block?

1. A and B

2. B and C

3. C and D

4. D and E

5. A, B and C

6. B, C and D

7. C, D and E

8. A, B, C and D

9. B, C, D and E

import java.io.*;

public class Quiz4 {

public static void main(String[] args) {

String line = null;

BufferedReader reader = null;

reader = new BufferedReader(

new FileReader("input.txt"));

line = reader.readLine();

reader.close();

}

}

ED

C

BA

Page 40: Handling errors Exception handling and throwing Simple file processing.

Text input

• Use the FileReader class• Augment with Scanner for line-based inputtry { Scanner in = new Scanner( new FileReader("name of file")); while(in.hasNextLine()) { String line = in.nextLine(); do something with line } in.close();} catch(FileNotFoundException e) { the specified file could not be found}• IOExceptions from FileReader “swallowed” by Scanner

Page 41: Handling errors Exception handling and throwing Simple file processing.

Outline

• Input/output

• Text files

• Terminal / keyboard• Binary Files

Page 42: Handling errors Exception handling and throwing Simple file processing.

User input from terminal window

• Similar to reading from a text file– construct a Scanner from System.in– no closing needed

Scanner in = new Scanner(System.in); System.out.println("type a line of input:"); String input = in.nextLine(); do something with input

Page 43: Handling errors Exception handling and throwing Simple file processing.

QUIZ

What is written if file ”input.txt” does not exist?

1."IOException"

2."FileNotFoundException"

3."IOException”+”FileNotFoundException"

4. Something else is written

5. Compiler error: cannot have 2 catches

6. Compiler error: wrong order of catches

7. Other compiler error

try {

String line = null;

BufferedReader reader = new BufferedReader(

new FileReader("input.txt"));

line = reader.readLine();

reader.close();

} catch (IOException e) {

System.out.print ("IOException");

} catch (FileNotFoundException e) {

System.out.print ("FileNotFoundException");

}

Page 44: Handling errors Exception handling and throwing Simple file processing.

Outline

• Input/output

• Text files

• Terminal / keyboard

• Binary Files

Page 45: Handling errors Exception handling and throwing Simple file processing.

Object streams

• ObjectOutputStream class can save entire objects to disk

• ObjectInputStream class can read objects back in from disk

• Objects are saved in binary format (and streams are used)

• similar to text files:– open, read/write, close

Page 46: Handling errors Exception handling and throwing Simple file processing.

• Writing object to file:BankAccount b1 = ...;ObjectOutputStream out = new ObjectOutputStream(new

FileOutputStream("accounts.dat"));out.writeObject(b1);

• Reading object from file:ObjectInputStream in = new ObjectInputStream(new

FileInputStream("accounts.dat");BankAccount b2 = (BankAccount) in.readObject();

• Objects that are written to a file must be instances of a class implementing the Serializable interface:

public class BankAccount implements Serializable {...}

Serializable interface has no methods

readObject may throw a (checked) ClassNotFoundException

Page 47: Handling errors Exception handling and throwing Simple file processing.

Use container and write a single object

• Objects of any size written/read in a single statement:

ArrayList a = new ArrayList();

... // add many objects to array list

out.writeObject(a)

• java.util.ArrayList implements Serializable

• Objects stored in the array list must also be instances of a class implementing Serializable