1 tirgul no. 12 topics covered: h binary search trees h exception handling in java
TRANSCRIPT
1
Tirgul no. 12Tirgul no. 12
Topics covered:
Binary Search Trees Exception Handling in java
5
Class BinarySearchTreeClass BinarySearchTree
public class BinarySearchTree {
protected Node root;
//some constructors
//methods (on next slides);
}
6
InorderTreeWalkInorderTreeWalk
public void inorderTreeWalk(){inorder(root);
}
//recursively traverse the tree:private void inorder(Node node)
if(node!=null) //stopping condition inorder(node.getLeft()); System.out.println(node.getData()); inorder(node.getRight());
}
7
SearchSearchpublic Node search(Comparable data){
return(treeSearch(root,data));}
//recursively search the tree:public Node treeSearch(Node node, Comparable data){
if( (node == null) || (node.getData().compareTo(data) == 0)
return(node);if(node.getData().compareTo(data) > 0) return(treeSearch(node.getLeft(),data);else return(treeSearch(node.getRight(),data);
}
8
InsertInsertpublic void insert(Comparable data){
Node currParent= null;Node node= root;while(node != null){
currParent= node;if(node.getData().compareTo(data) > 0 ) node= node.getLeft();else node= node.getRight();
}Node newNode= new Node(data);if( currParent == null) //tree is empty!
root= newNode;else if( currParent.getData().compareTo(data) > data)
currParent.setLeft(newNode)else
currParent.setRight(newNode);}
9
DeletionDeletionpublic Node delete(Comparable data){ Node delNode= search(data); if(delNode == null)
return; Node helper=null; Node temp= null;
//decide which node to splice: if( (delNode.getLeft() == null) ||
(delNode.getRight() == null) ) helper= delNode; else
helper= TreeSuccessor(delNode);//check for sons of splice node: if(helper.getLeft() != null) temp= helper.getLeft();
else temp= helper.getRight();
if(temp != null)temp.parent= helper.parent;
//check if successor is root nodeif(helper.getParent() == null)
root= temp;else if (helper == helper.getParent().getLeft() )
helper.getParent().setLeft(temp);else
helper.getParent().setRight(temp);if( helper != delNode)
//copy all fields of ydelNode.setData(helper.setData());
return(helper);}//end of method
10
• The way we deal with errors, exceptional/abnormal situations in the java programming language is by throwing exceptions.• Exceptions are instances of classes which are descendants of the class Exception.
Throwable
The Throwable family
Exception
descendants of Throwable
RunTimeExceptionGenerally work with this subtree
Exceptions
11
Exceptions: details
Many types of exceptions in java for examples look at java.lang api.
We can create our own types of exceptions by extending existing types.
Any Exception which is not a descendant of RuntimeException must be caught by a method or the method must be declared to throw the exception (more on this in a couple more slides).
12
Why do we use exceptions?
Make the code more readable - it separates the algorithm from error handling.
There are cases where returning a value to indicate errors is impossible or not reasonable - constructors and void methods.
Easier to indicate different types of errors.
Easy to propagate errors up the calling stack.
13
try {// guarded code.// exceptions A,B and C might be thrown here.
} catch (A a) {// what to do if A is thrown.
} catch (B b) {// handle B here.
} catch (C c) {// and here we have a chance to handle C.
} finally {// Thing that must happens after the rest of the code,// if an exception is thrown or not.
}
How to use Exceptions
14
We want to read a file into memory.
readFile (){ open the file; determine its size; allocate that much memory; read the file into memory; close the file;}
Example: Reading a file
15
int readFile() {openFile;if (file not opened) {
// handle the errorreturn -1;
}get the file length;if (cannot get the length) {
// handle this errorclose filereturn -2;
}allocate memory for the data;if (not enough memory) {
// another error to handle.close filereturn -3;
}
read data;if (read failed) {
// handle again.close file;return -4
}close file; // after read.reutrn 0; // success.
}
Reading file - without exceptions
16
void readFile() {try {
open file;get file size;allocate memory;read file;
} catch (FileNotOpened e1) {// handle this.
} catch (CannotGetFileLength e2) {// another handeling code.
} catch (MemoryAllocationFailed e3) {// yet another error.
} catch (ReadFailed e4) {// the last handle here.
} finally {if(file is open)
close file;}
}
This is the algorithm}
} Error handling
}code that happens in any case
Reading file - with exceptions
17
public class Example { public static void main(String args[]) { SimpleInput sin = new SimpleInput(System.in); int num;
boolean ok = false; while(!ok) { try { System.out.print("Enter an integer: "); num = sin.readlnInt(); ok = true; }catch(NumberFormatException nfe) { System.err.println("Read (" + nfe.getMessage() + ") not an integer."); }catch(IOException ioe) { System.err.println("Fatal IO error.\n"+ ioe + "Exiting program."); System.exit(1); } } }}
Recovering from errors
18
public class NimBoard { private int heaps[];
public NimBoard(int size) throws IllegalSizeException { if(size<1) throw new IllegalSizeException(size); heaps = new int[size]; }
// other methods of NimBoard}
Throwing exception from the constructor
19
public class IllegalSizeException extends IllegalArgumentException { public IllegalSizeException() {
super(); } public IllegalSizeException(String message) {
super(message); } public IllegalSizeException(int size) { super("Illegal nim board size ( " + size + ")"); }}
Defining a new exception type
20
Throwable
Exceptiondescendants of Throwable
RunTimeException
any class other than RunTimeException
descendants of RuntimeException
checkedunchecked
Checked versus Unchecked Exceptions