Handling errors - PowerPoint PPT Presentation

1 / 43
About This Presentation
Title:

Handling errors

Description:

Checked and unchecked exceptions. Java. Key words: try-catch-finally, throw, throws ... Unchecked exception. subclass of RuntimeException. use for unanticipated ... – PowerPoint PPT presentation

Number of Views:85
Avg rating:3.0/5.0
Slides: 44
Provided by: gudmundsko
Category:

less

Transcript and Presenter's Notes

Title: Handling errors


1
Handling errors
  • Exception handling and throwing
  • Simple file processing

2
Outline
  • Error example
  • Defensive Programming
  • Throwing Exception
  • Catching Exception
  • Defining new Exception Types
  • Checked vs unchecked

3
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

4
Example Runtime error
  • Use
  • AddressBook friends new AddressBook()
  • friends.removeDetails("frederik")
  • Result
  • java.lang.NullPointerException
  • at AddressBook.removeDetails(AddressBook.java119
    )
  • ...
  • 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 book
2. trying to call method on null results in
exception
5
Outline
  • Error example
  • Defensive Programming
  • Throwing Exception
  • Catching Exception
  • Defining new Exception Types
  • Checked vs unchecked

6
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

7
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
8
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

9
Returning a diagnostic
did any errors arise?
  • 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

10
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

11
Outline
  • Error example
  • Defensive Programming
  • Throwing Exception
  • Catching Exception
  • Defining new Exception Types
  • Checked vs unchecked

12
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

13
Throwing an Exception
  • public ContactDetails getDetails(String key)
  • if (keynull)
  • 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 ...

14
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

15
Outline
  • Error example
  • Defensive Programming
  • Throwing Exception
  • Catching Exception
  • Defining new Exception Types
  • Checked vs unchecked

16
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

17
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
18
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.
  • ...

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

20
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

21
Outline
  • Error example
  • Defensive Programming
  • Throwing Exception
  • Catching Exception
  • Defining new Exception Types
  • Checked vs unchecked

22
Defining new exceptions
  • Extend Exception or RuntimeException
  • Define new types to give better diagnostic
    information
  • include reporting and/recovery information

23
The exception class hierarchy
24
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

25
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

26
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

27
The throws clause
  • Methods throwing a checked exception must include
    a throws clause
  • public void saveToFile(String destinationFile)
    throws IOException ...

28
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."

29
QUIZ
IOException
XXX
NullPointerException
30
QUIZ
IOException
XXX
NullPointerException
31
Outline
  • Input/output
  • Text files
  • Terminal / keyboard
  • Binary Files

32
Input-output
  • Input-output is particularly error-prone
  • it involves interaction with the external
    environment
  • java.io.IOException is a checked exception

33
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
    4825657)
  • Use InputStream and OutputStream (and their
    subclasses)
  • (based on byte type)

34
Outline
  • Input/output
  • Text files
  • Terminal / keyboard
  • Binary Files

35
Text output
  • Use the FileWriter class
  • open a file
  • write to the file
  • close the file
  • Failure at any point results in an IOException.

36
Text output
  • try
  • 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

37
Text input
  • Use the FileReader class
  • Augment with Scanner for line-based input
  • try
  • 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

38
Outline
  • Input/output
  • Text files
  • Terminal / keyboard
  • Binary Files

39
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

40
Outline
  • Input/output
  • Text files
  • Terminal / keyboard
  • Binary Files

41
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

42
  • Writing object to file
  • BankAccount b1 ...
  • ObjectOutputStream out new ObjectOutputStream(ne
    w
  • 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
    ...

readObject may throw a (checked)
ClassNotFoundException
Serializable interface has no methods
43
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
Write a Comment
User Comments (0)
About PowerShow.com