CS 200 Command-Line Arguments & Exceptions

Slides:



Advertisements
Similar presentations
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Advertisements

Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Testing and Error Handling Intro to Java. Testing We test to try and make sure our programs work correctly and have no bugs If we have access to the code,
Exception Handling. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Files and Streams CS 21a Chapter 11 of Horstmann.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
1 Features of Java (2) CS 3331 Sections 4.5 and 4.6.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Exceptions In this lecture:
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Tirgul 13 Exceptions 1.
MIT AITI 2003 Lecture14 Exceptions
Testing and Debugging.
Introduction to Exceptions in Java
Introduction to OO Program Design
CS102 – Exceptions David Davenport Latest: May 2015
Creating and Modifying Text part 2
CS Week 10 Jim Williams, PhD.
CSE 501N Fall ’09 17: Exception Handling
CS Week 14 Jim Williams, PhD.
Exceptions 10-Nov-18.
CS 302 Week 15 Jim Williams, PhD.
Exceptions 10-Nov-18.
CS Week 11 Jim Williams, PhD.
What/how do we care about a program?
CS 200 File Input and Output
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
CS 200 Command-Line Arguments & Exceptions
Exception Handling Chapter 9.
ATS Application Programming: Java Programming
Exceptions & exception handling
Chapter 12 Exception Handling
File I/O ICS 111: Introduction to Computer Science I
Exception Handling Chapter 9 Edited by JJ.
Exception Handling.
CS 200 More Primitives, Objects, Branches and Methods
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Exception Handling in Java
Web Design & Development Lecture 7
CS 302 Week 13 Jim Williams, PhD.
Lecture 11 Objectives Learn what an exception is.
CMSC 202 Exceptions 2nd Lecture.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Tutorial Exceptions Handling.
Chapter 12 Exception Handling and Text IO Part 1
Tutorial MutliThreading.
CS 200 Command-Line Arguments & Exceptions
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Java Basics Exception Handling.
CMSC 202 Exceptions 2nd Lecture.
Java Programming: From Problem Analysis to Program Design, 4e
CS302 Week 6 Jim Williams.
Presentation transcript:

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