Handling errors
Exception handling and throwing Simple file processing
Exceptions
- Defensive programming
– Anticipating that something could go wrong
- Exception handling and throwing
- Example: File processing
- Java: try-catch-finally, throw, throws
- API: Exception, Stream, Reader/Writer
- terminal input
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
- TØ first week: explore error situations
Example: Runtime error
- In class AddressBook:
public void removeDetails(String key) { ContactDetails details = (ContactDetails) book.get(key); book.remove(details.getName()); ...}
- Use:
AddressBook book = new AddressBook(); book.removeDetails("frederik");
- Result:
java.lang.NullPointerException at AddressBook.removeDetails(AddressBook.java:119) ... returns null when key does not exist in book trying to call method on null results in Exception
Defensive programming
- Defense 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
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--; } }
- Similar modifications to other methods
check argument