CS 200 Command-Line Arguments & Exceptions Jim Williams, PhD
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
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]); // }
Text Interface vs GUI Interface
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.
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.
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]);
Command Line Arguments Passing to program from within Eclipse Passing to program from Command-Line
Various Kinds and Times for Errors Editing/Saving errors Compile time errors Syntax errors Runtime errors Logic errors Exceptions
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.
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");
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.
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
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
Exception Handling Hierarchy Categories Error - internal system errors Unchecked Exceptions Extend from RuntimeException Checked Exceptions Others that extend from Exception JavaDocs for Exceptions http://docs.oracle.com/javase/8/docs/api/ja va/lang/RuntimeException.html http://www.javamex.com/tutorials/exceptions/exceptions_hierarchy.shtml
ArrayIndexOutOfBounds is a checked exception an unchecked exception other B: an unchecked exception
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);
Checked Exceptions Compiler requires programmer to handle them. Must be handled, either: throws clause try - catch block
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"); }
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(); } }
Throwing Exceptions public void myMethod(int count) throws IllegalArgumentException { if ( count < 0) { throw new IllegalArgumentException( “count cannot be negative”); } //IllegalArgumentException is a RuntimeException
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 emailed (from Marc Renault) P7 & BP2 Eliza
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();
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?
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;
More Exceptions Exception Message What to do when you have to catch an exception and aren't sure yet how to handle? e.printStackTrace()
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
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
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.
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");
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);
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