170 likes | 273 Views
Tirgul no. 12. Topics covered : Binary Search Trees Exception Handling in java. Class BinarySearchTree. public class BinarySearchTree { protected Node root; //some constructors //methods (on next slides); }. InorderTreeWalk. public void inorderTreeWalk(){ inorder(root); }
E N D
Tirgul no. 12 Topics covered: • Binary Search Trees • Exception Handling in java
Class BinarySearchTree public class BinarySearchTree { protected Node root; //some constructors //methods (on next slides); }
InorderTreeWalk 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()); }
Search public 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); }
Insert public 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); }
public 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 node if(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 y delNode.setData(helper.setData()); return(helper); }//end of method Deletion
Exceptions • 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. The Throwable family Throwable descendants of Throwable Exception RunTimeException Generally work with this subtree
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).
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.
How to use Exceptions 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.}
Example: Reading a file 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; }
Reading file - without exceptions int readFile() { openFile; if (file not opened) { // handle the error return -1; } get the file length; if (cannot get the length) { // handle this error close file return -2; } allocate memory for the data; if (not enough memory) { // another error to handle. close file return -3; } read data; if (read failed) { // handle again. close file; return -4 } close file; // after read. reutrn 0; // success.}
Reading file - with exceptions 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 }
Recovering from errors 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); } } } }
Throwing exception from the constructor 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 }
Defining a new exception type public class IllegalSizeException extends IllegalArgumentException { public IllegalSizeException() { super(); } public IllegalSizeException(String message) { super(message); } public IllegalSizeException(int size) { super("Illegal nim board size ( " + size + ")"); } }
checked unchecked Checked versus Unchecked Exceptions Throwable Exception descendants of Throwable RunTimeException any class other than RunTimeException descendants of RuntimeException