Download presentation
Presentation is loading. Please wait.
Published byÊΠρομηθεύς Ζαφειρόπουλος Modified over 6 years ago
1
CS 200 Command-Line Arguments & Exceptions
Jim Williams, PhD
2
This Week Battleship: Milestone 3 Team Lab: ArrayLists
First impressions matter! Comment and style Team Lab: ArrayLists BP2, Milestone 1 next Wednesday shorter than typical, no Challenge Activities this weekend Lecture: Command-line arguments and Exceptions
3
BP2 Wa-Tor Planet of Wa-Tor Sharks and Fish population simulation
Image:
4
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]); // }
5
Text Interface vs GUI Interface
6
Command-Line Commands
Windows Unix/Linux/Mac dir cd mkdir rmdir del type help ls rm cat man
7
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.
8
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]);
9
Command Line Arguments
Passing to program from within Eclipse Passing to program from Command-Line
10
Various Kinds and Times for Errors
Editing/Saving errors Compile time errors Runtime errors New this week: Checked Exceptions are a mechanism where the compiler does some checks to make some errors visible at Compile time rather than Runtime.
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
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
Checked Exceptions Require exception handling code Unchecked Exceptions Programmer error, in general fix, don't wrap with handling code 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 Object o = new Object(); String d = (String)o; //ClassCastException Object o = null; o.toString(); //NullPointerException
15
Javadocs Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.String at Test.method2(Test.java:5) at Test.method1(Test.java:9) at Test.main(Test.java:27)
16
Exception Handling 3 Categories Error - internal system errors
Unchecked Exceptions RuntimeException Checked Exceptions Exception
17
ArrayIndexOutOfBounds is
a checked exception an unchecked exception other B: an unchecked exception
18
Checked Exceptions Compiler forces programmer to handle them.
Must be handled, either: catch declare the method throws
19
Throws clause //declare method throws them
public void myMethod() throws IOException { }
20
Catching Exceptions try { some statements; } catch ( Exception1 e) {
21
Throwing Exceptions public void myMethod(int i) throws IllegalArgumentException { if ( i < 0) { throw new IllegalArgumentException( “i 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)
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.