CS 367 Introduction to Data Structures Lecture 3.

Slides:



Advertisements
Similar presentations
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Advertisements

CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Testing and Error Handling Intro to Java. Testing We test to try and make sure our programs work correctly and have no bugs If we have access to the code,
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
交通大學資訊工程學系 Programming in Java Exception Handling 蔡文能 交通大學資訊工程學系
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
Cmp Sci 187: Midterm Review Based on Lecture Notes.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
12.1 Exceptions The limitations of traditional methods of exception handling Error conditions are a certainty in programming Programmers make.
Fall 2007CS 225 Program Correctness and Efficiency Chapter 2.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
SIGCSE Tradeoffs, intuition analysis, understanding big-Oh aka O-notation Owen Astrachan
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Program Errors Syntax errors Logic errors
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
Analysis of Algorithms
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Question of the Day  A landscaper plants 5 rows of 4 trees each, but only uses 10 trees. How is this possible?
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
What/how do we care about a program? Robustness Correctness Efficiency (speed, space) 11/2/20151IT 179  Software Testing  Error Handling  Efficiency.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Algorithm Analysis (Big O)
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
Exceptions Lecture 11 COMP 401, Fall /25/2014.
LECTURE 8: EXCEPTIONS CSC 212 – Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May.
Question of the Day completes starts  What word completes the 1 st word & starts the 2 nd one: DON???CAR.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Testing with JUnit, Introduction to Analysing Costs 2013-T2 Lecture 10 School of Engineering and Computer Science, Victoria University of Wellington 
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Introduction to Exceptions in Java CS201, SW Development Methods.
Section 3.3 Exceptional Situations. 3.3 Exceptional Situations Exceptional situation Associated with an unusual, sometimes unpredictable event, detectable.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Java Exceptions a quick review….
EECE 310: Software Engineering
Chapter 10 – Exception Handling
Introduction to Exceptions in Java
CS Week 10 Jim Williams, PhD.
Exceptions 10-Nov-18.
What/how do we care about a program?
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Lecture 11 Objectives Learn what an exception is.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Presentation transcript:

CS 367 Introduction to Data Structures Lecture 3

Iterators Most ADTs in Java can provide an iterator object, used to traverse all the data in an ADT.

Iterator Interface public interface Iterator { boolean hasNext(); E next(); void remove(); // Optional }

Getting an Iterator You get an iterator from an ADT by calling the method iterator(); Iterator iter = myList.iterator();

Now a simple while loop can process each data value in the ADT: while(iter.hasNext()) { process iter.next() }

A Simple Print method for Lists void printArrayList(){ Iterator iter = this.iterator(); while(iter.hasNext()){ System.out.print(iter.next()+" "); } System.out.println(); }

Adding Iterators to SimpleArrayList is easy First, we add the iterator() method to SimpleArrayList : public Iterator iterator(){ return new ArrayListIterator (this) ; }

Then we implement the iterator class for Lists: import java.util.*; public class ArrayListIterator implements Iterator { // *** fields *** private SimpleArrayList list; private int curPos; public ArrayListIterator( SimpleArrayList list) { this.list = list; curPos = 0; }

public boolean hasNext() { return curPos < list.size(); } public E next() { if (!hasNext()) throw new NoSuchElementException(); E result = list.get(curPos); curPos++; return result; } public void remove() { throw new UnsupportedOperationException(); }

Empty vs. Null In Java all objects are accessed through a reference. A reference may be null. This is not the same as a data object that has nothing in it. Consider String str1 = “”; String str2 = null; str1 references something (the empty string) str2 references nothing.

Java Exceptions Sometimes a program must signal a programming error or an illegal or impossible call. Programming errors include trying to access a null reference or using an invalid array index.

Illegal calls might involve trying to access the records of an non-existent patient or plotting a route to an impossible destination. Java programs signal an illegal or impossible operation by throwing an exception.

Uncaught Exceptions In the simplest case, a thrown exception is uncaught. It forces each pending method call to return. Finally, the Java runtime system terminates execution with an error message and a walk-back trace.

Exception in thread "main" java.lang.NullPointerException at ExceptionTester.methodC(ExceptionTester.java:110) at ExceptionTester.methodB(ExceptionTester.java:89) at ExceptionTester.methodA(ExceptionTester.java:72) at ExceptionTester.main(ExceptionTester.java:49) A null pointer error occurred in methodC at line 110. methodC was called by methodB at line 89. methodB was called by methodA at line 72. methodA was called by main at line 49.

Catching exceptions We can catch exceptions using a try-catch block: try { // Java code that might throw an exception} catch (ExceptionType id1 { // Java code to handle the caught exception } If code in the try block throws an exception (directly or indirectly), execution in the try stops. If the thrown exception matches (or is a subclass of) ExceptionType, code in the catch block is executed. Then execution resumes after the try-catch. If no exception is thrown, just the try block executes.

An Example of try-catch static void planA(int i) throws PlanAFailed { if (i == 1) throw new PlanAFailed(); else System.out.println("Plan A worked");} static void planB(){ System.out.println("Plan B worked"); } for (int i = 1; i <= 2; i++) try { planA(i); } catch (PlanAFailed exc) { planB(); }

Output is: Plan B worked Plan A worked

Multiple Catch Blocks are Allowed try{ // Java code that might throw an exception} catch (ExceptionType1 id1 { // Java code to handle the caught exception } catch(ExceptionType2 id2 { // Java code to handle the caught exception } Catch blocks are tried in order (can thrown exception match declared exception?) If no catch matches, exception is passed to containing try block or caller of current method.

An Example of Multiple Catch Blocks static void tester(int i) throws InvalidFlag, SizeTooLarge { if (i == 1) throw new InvalidFlag(); if (i == 2) throw new SizeTooLarge(); else throw new NullPointerException();} for (int i = 1; i <= 3; i++) try { tester(i); } catch (InvalidFlag exc) { System.out.println("Invalid flag in call"); } catch (SizeTooLarge exc) { System.out.println("Data set too large"); }

Output is: Invalid flag in call Data set too large Exception in thread "main" java.lang.NullPointerException at ThrowTest.tester(throw2.java:10) at ThrowTest.main(throw2.java:16)

Exceptions are Java objects They must be a subclass of Throwable. Throwable has two subclasses, Error and Exception. Exceptions in Error usually aren’t caught (they usually are unrecoverable). Exceptions in Exception may be caught. A subclass of Exception is RuntimeException.

Exceptions in RuntimeException often are not caught (e.g., NullPointerException ). They need not be checked for. Exceptions in Exception but not in RuntimeException are called checked. They must be handled. How? A method that may raise a checked exception may guarantee that it is handled by that method. “What happens in Vegas stays in Vegas!”

Alternatively a method may warn in its header that one or more checked exceptions may be returned to the caller (who can handle them or pass them back to its caller.) static void tester(int i) throws InvalidFlag, SizeTooLarge { … }

An “Exception Tester” public static void main(String[] args) { if (args.length != 2) { method = " "; color = " "; } else { method = args[0]; color = args[1]; } System.out.print("main["); try { methodA(); System.out.print("after A, "); methodE(); System.out.print("after E,"); } catch (RedException exc) { System.out.print("red,");} catch (GreenException exc) { System.out.print("green,"); System.out.println("]main"); }

private static void methodA() { System.out.print("A["); try { methodB(); System.out.print("after B,");} catch (BlueException exc) { System.out.print("blue,”); System.out.print("]A "); }

private static void methodB() { System.out.print("B["); try {methodC(); System.out.print("after C,");} catch (YellowException exc) { System.out.print("yellow,"); throw new GreenException(); } catch (RedException exc) { System.out.print("red,"); } methodD(); System.out.print("after D"); System.out.print("]B "); }

methodC, methodD and methodE all behave the same: If the method field matches their name, they throw an exception corresponding to the color field. Otherwise they do nothing but return.

Basic execution sequence Below is a call tree. If no exceptions are thrown, execution sequence is depth-first: Main E A B CD

The generated trace is: main[ A[ B[ after C, after D ]B after B,]A after A, after E, ]main

We alter execution order by throwing an exception We direct C, D or E to throw an exception by setting the method field and the color field. So method = "c"; color = "blue"; tells C to throw a blue exception.

The execution trace is now: main[ A[ B[blue,]A after A, after E, ]main Why? C throws blue. Its caller, B, doesn’t catch blue exceptions, so it is passed to B’s caller, A. A handles the exception, returns to main, and E is then called.

Try another: method = ”e"; color = "blue"; main[ A[ B[after C, after D]B after B,]A after A Exception in thread "main" BlueException

Additional Tests You can run 15 different tests (3 methods, 5 exceptions). You should try several to perfect your understanding. You can: 1. Run a test, then study the source to understand why the trace was generated. 2. Predict what a test will do, then run the program to verify your prediction.

Analyzing Algorithm Efficiency The complexity of an algorithm is how it uses resources like CPU time or memory. How does the cost scale as the problem size grows?

Some computations are constant time – no change as problem size grows. Example: remove operation in a Bag ADT Some computations grow linearly – double the size means double the time. Example: finding a value in an unsorted array.

Some computations grow as the square – double the size means four times the time. Example: many simple sorts. Some computations grow much faster – exponentially or worse. Example: magic square

N vs. N log(N) vs. N 2

N vs. N log(N) vs. N 2 vs. 2 N NN log(N)N2N2 2N2N ,048, ,0001.3* ,000,0001.1*10 301

What’s this log business? Log is logarithm. Remember that an exponent tells us how many times a number is to be multiplied: 10 3 means 10*10*10 A logarithm tells us what exponent is needed to produce a particular value. Hence log 10 (1000) = 3 since 10 3 = 1000.

Fractional exponents (and logs) are allowed √x = x 0.5 This is because √x * √x = x, so x 0.5 * x 0.5 = x 1 = x Thus log 10 (√x) = 0.5 * log 10 (x).

What base do we use? Usually base 2, but … it doesn’t really matter. Logs to different bases are related by a constant factor. Log 2 (x) is always 3.32… bigger than log 10 (x). Because … = 10

Many useful algorithms are n log(n) is complexity This is way better than an n 2 algorithm (because log(n) grows slowly as n grows).

Example: Giving a Toast 1. Fill the glasses. Linear complexity 2. Raise glasses & give the toast Constant time 3. Clink glasses. Person 1 clinks with persons 2 to N Person 2 clinks with persons 3 to N … Person N-1 clinks with person N

Total number of clinks is (n-1)+(n-2)+ … This sums to n*(n-1)/2 = n 2 /2 – n/2. So this step is quadratic.

Big O Notation This is a notation that expresses the overall complexity of an algorithm. Only the highest-order term is used; constants, coefficients, and lower-order terms are discarded. O(1) is constant time. O(N) is linear time. O(N 2 ) is quadratic time. O(2 N ) is exponential time.

The three functions: 4N 2 +3N+2, 300N 2, N(N-2)/2 Are all O(N 2 ).

Formal Definition A function T(N) is O(F(N)) if for some constant c and threshold n 0, it is the case T(N) ≤ c F(N) for all N > n 0

Example The function 3n 2 -n+3 is O(n 2 ) with c =3 and n 0 = 3: n3n 2 -n+33n