pages.cs.wisc.edu

pages.cs.wisc.edu

CS 200 Command-Line Arguments & Exceptions Jim Williams, PhD This Week 1. Chap 9 zyLabs: Get started 2. Grading Code Refactor 1: Wumpus Caves a. Anticipate results returned to you early next week. b. Regrade request: 1 week from when returned. 3. Team Lab: ArrayLists, Debugging

4. Lecture: a. Finish up ArrayLists b. Command-line arguments and Exceptions i. Enough for Text File Input and Output next week. Draw a Diagram & TopHat ArrayList> list = new ArrayList<>(); list.add( new ArrayList()); list.add( new ArrayList()); list.add(1, new ArrayList());

list.get(1).add("D"); list.set(0, list.get(1)); list.get(2).clear(); System.out.println( list); [[],[],[]] [[], [D], []] [[D],[D],[]] error or other TopHat: What is printed out?

ArrayList list4; list4 = new ArrayList(100); for ( int i = 0; i < 1000; i++) { list4.add( i); } System.out.println( list4.size()); TopHat: Write the code. With the goal of minimizing the running time of your program, how would you declare and instantiate an ArrayList, called temps, to store

a sequence of at least 100,000 temperature measurements? TopHat: What size and elements? ArrayList list; list = new ArrayList(); list.add("A"); list.add(0,"B"); list.add("C"); list.set(2,"D"); list.add("E");

System.out.println( list); 5 [A,B,C,D,E] 4 [B, A, D, E] 3 [B,D,E] error or other Text Interface vs GUI Interface

Command Prompt (Windows) Terminal (Mac/Linux) Command-Line Commands Windows Linux/Mac dir cd mkdir rmdir del type

help ls cd mkdir rmdir rm cat man description

show dir. contents change directory make directory remove directory remove files show file contents show help info. Command-Line Arguments java ClassName arg0 arg1 arg2 Arguments passed to the program when run

arg0, arg1, arg2 are passed to the ClassName program. Become arguments to the main method e.g.: String [] args = {"arg0", "arg1", "arg2"}; public class ClassName { public static void main(String []args) {... } From the 1st Week public class CmdLine {

public static void main(String[] args) { } } Command-Line Arguments Passing to program from within Eclipse Passing to program from Command-Line TopHat: What is the output: java CmdLine this is "the question" public class CmdLine {

public static void main(String[] args) { String str = ""; for ( int i = 0; i < args.length; i++) { str = args[i] + str; } System.out.print( str); } Exercise: Switches Print out all the command line arguments. If the -s argument is found then put a space

between them, otherwise concatenate. If the -r argument is found then print out in reverse order. Exceptions An exceptional/unusual event Interrupts normal program execution Starts exception handling program execution What causes these events? An installation or machine error

A programming error A user error Exception Class Hierarchy Instances of Throwable or descendants can be thrown and caught. Internal system errors (unchecked by compiler)

Errors Frequently abnormal conditions beyond the programmer's control. Examples: java.lang.OutOfMemoryError java.lang.InternalError java.lang.VirtualMachineError Exception Class Hierarchy Frequently programmer

error (unchecked by compiler) Runtime Exception Typically programming errors, that should be fixed. Examples: java.lang.NullPointerException java.lang.ArrayIndexOutOfBoundsExcepti on java.lang.StringIndexOutOfBoundsExcept

ion Exception Class Hierarchy Checked Checked Checked Checked means: compiler verifies that the program handles with either

try block or throws clause Checked vs Unchecked Unchecked exceptions usually mean the program cannot recover and so program ends. Instances of Error and RuntimeException and descendants.

Checked exceptions A method must handle with either try block throws clause Unchecked Exceptions Examples int result = 1 / 0; //ArithmeticException int[] list = new int[4];

System.out.print( list[4]); //ArrayIndexOutOfBoundsException String s = abc; System.out.print( s.charAt(3)); //StringIndexOutOfBoundsException String s2 = null; System.out.print( s2.charAt(3)); //NullPointerException TopHat: What kind is InputMismatchException? import java.util.Scanner; public class ExceptionExercise {

public static void main(String[] args) { Scanner in = new Scanner ("blue"); double value = in.nextDouble(); System.out.println("Value is " + value); } } Stack Trace When an exception is thrown it records the context the exception occurred. Optionally print out: Stack Trace

Exception in thread "main" java.lang.ArithmeticException: / by zero at Arith.divide(Arith.java:3) at Arith.main(Arith.java:6) TopHat: What method & line in your code? Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextDouble(Scanner.java:2413) at ExceptionExercise.getValue(ExceptionExercise.java:5)

at ExceptionExercise.main(ExceptionExercise.java:9) Checked Exceptions Compiler requires programmer to handle with: throws clause try block Examples: java.io.IOException java.io.FileNotFoundException java.net.SocketException

TopHat: ArrayIndexOutOfBounds is a checked exception an unchecked exception other Throwing Exceptions IllegalArgumentException is a RuntimeException public void myMethod(int count) throws IllegalArgumentException { if ( count < 0) { throw new IllegalArgumentException( count cannot be negative);

} } Initiates exception handling Throws clause In method definition, declare method may throw the exception public void myMethod() throws FileNotFoundException { //the following code may throw a Throws clause

FileNotFoundException FileReader reader = new FileReader("filename.txt"); } Try Catch Block In method definition, catch exception public void myMethod() { try block try { //the following code may throw a FileNotFoundException

FileReader reader = new FileReader("filename.txt"); } catch ( FileNotFoundException e) { e.printStackTrace(); } } Demo: Unchecked to Checked public class Arith { public static int divide( int num, int denom) { return num / denom; }

public static void main(String[] args) { System.out.print( divide( 1, 0)); } } TopHat: Question What tool checks whether checked exceptions are handled? Editor Compiler

JVM None - only unchecked exceptions are checked. Demo: Interpreting an Exception Stack Trace Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(Unknown Source)

at Interpret.methodY(Interpret.java:7) at Interpret.methodZ(Interpret.java:10) at Interpret.main(Interpret.java:3) Exercise: Exception Stack Trace Exception in thread "main" java.lang.NullPointerException at TestException.method2(TestException.java:6) at TestException.method1(TestException.java:3) at TestException.main(TestException.java:13) TopHat: What prints out when exception is thrown?

Exception 1 thrown here; try { System.out.println("A"); System.out.println("B"); } catch( Exception1 e) { System.out.println("C"); } catch( Exception2 e) { System.out.println("D"); } finally { System.out.println("E"); }

TopHat: What prints out when the Exception is thrown? try { System.out.print("A"); Exception 1 thrown here; System.out.print("B"); } catch( Exception1 e) { System.out.print("C"); } catch( Exception2 e) { System.out.print("D"); } finally {

System.out.print("E"); } System.out.print("F"); TopHat: What prints out? try { System.out.println("A"); System.out.println("B"); } catch( Exception1 e) { System.out.println("C"); Exception 1 thrown here;

} catch( Exception2 e) { System.out.println("D"); } finally { System.out.println("E"); } System.out.println("F"); TopHat: What prints out when the Exception is thrown? try { System.out.println("A"); Exception 1 thrown here;

System.out.println("B"); } catch( Exception1 e) { System.out.println("C"); throw e; } catch( Exception2 e) { System.out.println("D"); } finally { System.out.println("E"); } System.out.println("F");

TopHat: What prints out when the Exception is thrown? try { System.out.println("A"); Exception 3 (sibling of 1 & 2) thrown here; System.out.println("B"); } catch( Exception1 e) { System.out.println("C"); } catch( Exception2 e) { System.out.println("D"); } finally { System.out.println("E");

} System.out.println("F"); TopHat: What prints out when the Exception is thrown? try { System.out.println("A"); System.out.println("B"); } catch( Exception1 e) { System.out.println("C"); } catch( Exception2 e) { System.out.println("D");

} finally { System.out.println("E"); Exception 1 thrown here; } System.out.println("F"); Not Sure How To Handle Exception? When you must catch an exception and aren't sure yet how to handle? Just call printStackTrace() so the exception isn't hidden. try {

//open and read from file } catch ( FileIOException e) { e.printStackTrace(); } TopHat: If this compiles, what is true? static void methodB(int i) { if ( i < 3) throw new ExceptionQ(); }

public static void main(String[] args) { try { methodB( 2); System.out.print("B"); } catch( ExceptionQ e) { System.out.print("C"); } finally { System.out.print("D"); } System.out.print("E");

ExceptionQ is an checked exception CDE is printed D only is printed BDE is printed Handling Command Line Arguments A program that reverses and/or upper cases whatever is typed in. Usage: java Process [-r] [-u] java Process -r -u

This is some text TXET EMOS SI SIHT And more EROM DNA Walk Through Testing with a Debugger Set breakpoints on each branch path Run program in Debugger stepping through each statement Verify execution by predicting and then verifying values in variables

Remove breakpoint when segment verified Repeat creating conditions until all branch paths are executed and all breakpoints removed Common Algorithms Searching Sorting Linear Search //Returns the index of where the element x was //found or -1 if not found.

public static int linearSearch( ArrayList list, int x) { } Binary Search // Return index of where x is in list if found, // otherwise returns -1; public static int binarySearch(ArrayList list, int x) {

} Sorting Demo 9, 6, 4, 5, 8, 2

Recently Viewed Presentations

  • M 2 . 1 n o s s

    M 2 . 1 n o s s

    The Systeme International d'Unites (SI) is the system of units scientists agreed on for measurements. There are only seven base units. These units can be combined to form derived units. It is referred to as the meter-kilogram-second system.
  • Searching alternative sources Document discovery in integrated care

    Searching alternative sources Document discovery in integrated care

    Supporting people to be independent - care in your own home / services/technology. Avoiding unplanned admissions - e.g. falls - Channel shift. Every service in the NHS has nationally set priorities, targets and budget constraints, etc. Increasingly, solutions are looking...
  • Título da Palestra

    Título da Palestra

    Crescimento. O mercado de acesso e usuários Internet vem crescendo a taxas significativas no Brasil, em torno de 15% ao ano. O e-commerce, "transações através Internet" vem crescendo a taxas ainda mais aceleradas (25% ao ano)
  • Superman Bearings Superman Bearings Superman has to fly

    Superman Bearings Superman Bearings Superman has to fly

    Superman Bearings. Superman has to fly around his local area catching criminals. He obviously flies in a straight line between cities and towns as that is the quickest route. Use bearings and a scale of . 1cm:50km. to describe Superman's...
  • Third Thursday Webinar CHC Monitoring Report Update April

    Third Thursday Webinar CHC Monitoring Report Update April

    Purpose: Monthly report that identifies all services that were not delivered for participants who utilize home health skilled care, home health aide services and personal assistance services. This report also identifies all non-delivered or late trips for medical, non-emergency medical...
  • Stora Enso Oyj - PPT Template A4 - UTK

    Stora Enso Oyj - PPT Template A4 - UTK

    We use LU factorization to avoid matrix operations. LU Factorization and L: lower triangular matrix, U: upper triangular matrix So, we have Design Details Combine L and U into one matrix, therefore saving more place. Use long vector to define...
  • Squid Dissection - School District of the Chathams

    Squid Dissection - School District of the Chathams

    External Anatomy. Eyes. Theses are much like our own, but the lens is shaped like a football (ours is round). If you carefully snip open the eye you can remove the hard lens with you fingers. Squid can tell the...
  • Chapter 9 Buffer Zones and Posting Requirements

    Chapter 9 Buffer Zones and Posting Requirements

    TEMPERATURE INVERSIONS. Temperature inversion conditions typically start an hour before sunset and continue past sunrise. They may persist as late as noontime. However, inversions can persist all day long. Inversion conditions are . common on nights with . limited cloud...