Download presentation
Presentation is loading. Please wait.
1
CS 200 Command-Line Arguments & Exceptions
Jim Williams, PhD
2
This Week MasterMind: Milestone 3 Team Lab: ArrayLists, Debugger
Let's count: * ! - Thoroughly test methods First impressions matter! Comment and style Team Lab: ArrayLists, Debugger TA Review Session Lecture: Command-line arguments and Exceptions
3
Command-Line Arguments
java ClassName arg0 agr1 arg2 arg0 arg1 and arg2 are arguments passed into the main method of the program, ClassName, when it is run.
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
Command-Line Arguments
Passing to program from within Eclipse Passing to program from Command-Line
6
Passing Command Line Arguments to a program within Eclipse
Run Menu>Run Configurations Choose correct Java Application in left Select Arguments tab type in the program arguments: this is "the question" Click Run
7
Text Interface vs GUI Interface
Command Prompt (Windows) Terminal (Mac/Linux)
8
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. Will use these in a lab.
9
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.println( str); the questionisthis
10
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. import java.util.ArrayList; public class Switches { //-s space separated //-r reverse order public static void main(String[] args) { ArrayList<String> values = new ArrayList<>(); boolean space = false; boolean reverse = false; for ( String arg : args) { if ( arg.equals("-s")) { space = true;} else if ( arg.equals("-r")) { reverse = true; } else { values.add( arg); } if ( reverse) { for ( int i = values.size() -1; i >= 0; i--) { if ( space) { System.out.print(values.get(i) + " "); } else { System.out.print(values.get(i)); for ( int i = 0; i < args.length; i++) {
11
Exceptions Java Language Specification:
12
Various Kinds and Times for Errors
Editing/Saving errors Compile time errors Syntax errors Runtime errors Logic errors Exceptions
13
Exceptions When a program violates a semantic constraint of the programming language. The program cannot continue running through the normal instruction sequence. We use try-catch-finally blocks and throws clause to modify exception handling sequence. Java Language Specification:
14
Exceptions 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) public class Arith { public static int divide( int num, int denom) { return 1 / 0; } public static void main(String[] args) { System.out.print( divide( 1, 0));
15
Notes BP1 Milestone 3 Due today
Offline and Human Grade: Highest scoring, last submission by 11:59pm. For teams, we choose one partner's work to grade and assign both the same grade. (both must turn in) Grading Big Programs - process BP2 Adventure Story available - M1 due next week P7 available - due May 2
16
Unchecked Exceptions 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
17
What line is an exception thrown?
import java.util.Scanner; public class ExceptionExercise { public static void main(String[] args) { Scanner in = new Scanner ("twenty"); double value = in.nextDouble(); System.out.println("Value is " + value); } Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextDouble(Unknown Source) at ExceptionExercise.main(ExceptionExercise.java:5)
18
Checked Exceptions Compiler requires programmer to handle with:
throws clause try block Consequently, checked exceptions can be verified as handled at compile time rather than runtime.
19
ArrayIndexOutOfBounds is
a checked exception an unchecked exception other B: an unchecked exception
20
Is InputMismatchException a checked exception?
import java.util.Scanner; public class ExceptionExercise { public static void main(String[] args) { Scanner in = new Scanner ("twenty"); double value = in.nextDouble(); System.out.println("Value is " + value); } Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextDouble(Unknown Source) at ExceptionExercise.main(ExceptionExercise.java:5)
21
3 Categories of Throwables
Unchecked Exceptions May have try block or throws clause Example: ArrayIndexOutOfBounds Checked Exceptions Must have try block or throws clause Example: FileNotFoundException Errors System configuration and other VM problems
22
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
23
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)); Modify to add throws and try catch
24
Throwing Exceptions public void myMethod(int count) throws IllegalArgumentException { if ( count < 0) { throw new IllegalArgumentException( “count cannot be negative”); } //IllegalArgumentException is a RuntimeException
25
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"); }
26
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(); } }
27
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.
28
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();
29
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);
30
What prints out when the 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"); } System.out.println("F"); nothing. Since not in a try block all the remaining code in the method will be skipped.
31
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"); } catch( Exception2 e) { System.out.println("D"); } finally { System.out.println("E"); } System.out.println("F"); ACEF
32
What prints out when the Exception is thrown?
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"); ABEF catch with exception is never executed and so the exception won't be thrown
33
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"); Exception 1 rethrown here; } catch( Exception2 e) { System.out.println("D"); } finally { System.out.println("E"); } System.out.println("F"); ACE
34
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"); AE
35
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"); nothing
36
More Exceptions Exception Message
What to do when you have to catch an exception and aren't sure yet how to handle? e.printStackTrace()
37
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
38
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
39
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 ExceptionQ is an unchecked exception. D: CDE is printed.
40
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);
41
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.