Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 200 Command-Line Arguments & Exceptions

Similar presentations


Presentation on theme: "CS 200 Command-Line Arguments & Exceptions"— Presentation transcript:

1 CS 200 Command-Line Arguments & Exceptions
Jim Williams, PhD

2 This Week Sokoban: Milestone 3 Team Lab: ArrayLists TA Review Session
First impressions matter! Comment and style Team Lab: ArrayLists TA Review Session Lecture: Command-line arguments and Exceptions

3 From the 1st Week public class CmdLine {
public static void main(String[] args) { } //To test command line arguments in Eclipse //Run>Run Configurations… then select Arguments tab and enter the arguments and click run. public class CmdLine { public static void main(String[] args) { if ( args.length < 1) { System.out.println("Usage: java CmdLine name"); } else { System.out.printf("hello %s", args[0]); } // System.out.println( args); // // for ( int i = 0; i < args.length; i++) { // System.out.println( args[i]); // }

4 Text Interface vs GUI Interface

5 Command-Line Commands
Windows Linux/Mac description dir cd mkdir rmdir del type help ls rm cat man show dir. contents change directory make directory remove directory remove files show file contents show help info.

6 What are command-line arguments?
an array of Strings information passed into the program the main method parameter public class CmdLine { public static void main(String[] args) { System.out.println( args.length); for ( int i = 0; i < args.length; i++) { System.out.println( args[i]); } All are true The main method parameter is named args that is an array of Strings that contains information passed into the program.

7 Usage Message public class UseCmd{
public static void main(String[] args) { if ( args.length != 1) { System.out.println( "Usage: java CmdLine filename"); System.exit( 1); //0 success, non-zero error } System.out.println( "Filename: " + args[0]);

8 Command Line Arguments
Passing to program from within Eclipse Passing to program from Command-Line

9 Various Kinds and Times for Errors
Editing/Saving errors Compile time errors Syntax errors Runtime errors Logic errors Exceptions

10 New This Week Runtime errors Logic errors Exceptions
Unchecked Exceptions Checked Exceptions Checked Exceptions are a mechanism where the compiler does some checks to make sure error handling is in place. These Compile time checks can save some Runtime problems.

11 Demo Unchecked vs Checked Exceptions
public static double profitMargin( double profit, int numSales){ return profit / numSales; } public static void main(String[] args) { int numSales = 10; double profit = 100.0; double profitMargin = profitMargin( profit, numSales); System.out.printf("sales = %d, profit = %.2f, profitMargin = %.2f\n", numSales, profit, profitMargin); public class Sales { public static double profitMargin( double profit, int numSales) throws Exception { if ( numSales == 0) { throw new Exception("Hey, numSales is 0, this is a problem with the calculations"); } return profit / numSales; public static void main(String[] args) { int numSales = 0; double profit = 0.0; try { double profitMargin = profitMargin( profit, numSales); System.out.printf("sales = %d, profit = %.2f, profitMargin = %.2f\n", numSales, profit, profitMargin); } catch ( Exception e) { e.printStackTrace(); System.out.println("after try-catch block");

12 Question What tool checks whether checked exceptions are handled?
Editor Compiler JVM None - only unchecked exceptions are checked. compiler is the best answer. In Eclipse errors are shown in the Editor because Eclipse is an Integrated Development Environment but it is compiler functionality that is checking that exceptions are handled and reporting to the Eclipse Editor to show the red line to the user.

13 3 Categories of Throwables
Unchecked Exceptions Fix problem, don't wrap with handling code Example: ArrayIndexOutOfBounds Checked Exceptions Require exception handling code Example: File not found Errors System configuration and other VM problems

14 Unchecked Exceptions - Programming Errors
System.out.println( 1 / 0); //ArithmeticException int[] list = new int[4]; System.out.println( list[4]); //ArrayIndexOutOfBoundsException String s = “abc”; System.out.println( s.charAt(3)); //StringIndexOutOfBoundsException String s2 = null; System.out.println( s2.charAt(3)); //NullPointerException

15 Exception Handling Hierarchy
Categories Error - internal system errors Unchecked Exceptions Extend from RuntimeException Checked Exceptions Others that extend from Exception JavaDocs for Exceptions va/lang/RuntimeException.html

16 ArrayIndexOutOfBounds is
a checked exception an unchecked exception other B: an unchecked exception

17 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) public class TestException { public static void method1(String str) { method2( str); } public static void method2(String str) { System.out.println( str.charAt(3)); public static void main(String[] args) { String s2 = null; if ( args.length > 0) { s2 = args[0]; method1( s2);

18 Checked Exceptions Compiler requires programmer to handle them.
Must be handled, either: throws clause try - catch block

19 Throws clause In method definition, declare method may throw the exception public void myMethod() throws FileNotFoundException { //the following code may throw a FileNotFoundException FileReader reader = new FileReader("filename.txt"); }

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

21 Throwing Exceptions public void myMethod(int count) throws IllegalArgumentException { if ( count < 0) { throw new IllegalArgumentException( “count cannot be negative”); } //IllegalArgumentException is a RuntimeException

22 Notes BP1 Milestone 3 Due today
Graded: Highest scoring, last submission by deadline. For teams, we choose one partner's work to grade and assign both the same grade. (both must turn in) Grading Big Programs Exam 2 Next Thursday Exam Conflict Alternatives have been ed (from Marc Renault) P7 & BP2 Eliza

23 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) public class Interpret { public static void main(String[] args) { methodZ(); } public static void methodY() { String str = ""; str.charAt(0); public static void methodZ() { methodY();

24 What happens when... try { statement1;
statement2; //throws an exception statement3; } catch( Exception1 e) { } catch( Exception2 e) { } statement4; //will statement 3 be executed? //if exception is not caught will statement 4 be executed? //if the exception is caught will statement 4 be executed?

25 What happens when... static int methodA() throws Exception5 { try {
statement1; statement2; statement3; } catch( Exception1 e) { statementE; throw new Exception5(“some message”); } finally { statement4; } Statement5; return 1;

26 More Exceptions Exception Message
What to do when you have to catch an exception and aren't sure yet how to handle? e.printStackTrace()

27 If methodA doesn't throw an exception then output is?
public static void main(String[] args) throws Exception { try { methodA( args); System.out.print("B"); } catch( Exception e) { ///write error to a log file System.out.print("C"); throw e; } finally { System.out.print("D"); } System.out.print("E"); BCDE CDE CD BDE try it

28 If methodA throws Exception then output is?
public static void main(String[] args) throws Exception { try { methodA( args); System.out.print("B"); } catch( Exception e) { //e.printStackTrace(); System.out.print("C"); //throw e; } finally { System.out.print("D"); } System.out.print("E"); BCDE CDE CD BDE try it

29 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( 3); 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 ExceptionQ is an unchecked exception. D: BDE is printed.

30 Interpreting an Exception Stack Trace
D Exception in thread "main" java.lang.Exception: java.lang.Exception: message at Interpret2.main(Interpret2.java:13) Caused by: java.lang.Exception: message at Interpret2.methodA(Interpret2.java:4) at Interpret2.main(Interpre t2.java:8) public class Interpret2 { public static void methodA( String [] list) throws Exception { throw new Exception("message"); } public static void main(String[] args) throws Exception { try { methodA(args); System.err.println("B"); } catch (Exception e) { /// May write error to a log file System.err.println("C"); throw new Exception(e); } finally { System.err.println("D"); System.err.println("E");

31 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 import java.util.Scanner; public class Process { public static String reverse(String str) { String result = ""; for ( int i = str.length() -1; i >=0; i--) { result += str.substring(i, i+1); } return result; public static void main(String[] args) { if ( args.length <= 0) { System.out.println("Usage: java Process [-r] [-u]"); System.exit( -1); boolean reverse = false; boolean upperCase = false; for ( String str : args) { switch ( str) { case "-r": reverse = true; break; case "-u" : upperCase = true; Scanner input = new Scanner(System.in); while ( input.hasNextLine()) { String line = input.nextLine(); if ( reverse) line = reverse(line); if ( upperCase) line = line.toUpperCase(); System.out.println( line);

32 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


Download ppt "CS 200 Command-Line Arguments & Exceptions"

Similar presentations


Ads by Google