CS 200 - Programming I: Exceptions Marc Renault Department of Computer Sciences University of Wisconsin Madison Fall 2017 TopHat Sec 3 (PM) Join Code: 719946 TopHat Sec 4 (AM) Join Code: 891624
Command-Line Arguments
1/31 Passing Command-Line Arguments Example: java CmdLineEx arg0 agr1 arg2 Command-Line Arguments Arguments passed to the program when it is launched. In example: arg0, arg1, arg2
1/31 Passing Command-Line Arguments Example: java CmdLineEx arg0 agr1 arg2 Command-Line Arguments Arguments passed to the program when it is launched. In example: arg0, arg1, arg2 String[] args Passed to the main method via the String[] args. In example: String[] args = {"arg0","arg1","arg2".
2/31 TopHat Question 1 What is the output when executed using the command java CmdLineEx Do or do not, there is no try. public class CmdLineEx { public static void main ( String [] args ) { int i = 0; for ( String s: args ) { i += s. length (); System. out. print (i);
3/31 Command-Line Argument Exercise Write a program that receives from the command line both a string and action to preform (either changing to upper case or lower case). The command-line arguments are organized as follows: -s str, where str is the string to transform -l to lowercase -u to uppercase There should only be one of -l or -u. The arguments should be handled in any order. After parsing the arguments, the program outputs the string, having converted to upper or lower case as per the command-line arguments.
Paths
4/31 Navigating the File System / home renault workspace
4/31 Navigating the File System /home/renault/workspace
Navigating the File System /home/renault/workspace CS200Ex bin Data In Out src Palindrome bin src OrdinalEx bin src CmdLine bin src 4/31
Navigating the File System /home/renault/workspace CS200Ex bin Data In Out src Palindrome bin src OrdinalEx bin src CmdLine bin src Current Working Directory (CWD) Current location in the file system. Denoted by:. The directory from which the jvm was launched. 4/31
Navigating the File System /home/renault/workspace CS200Ex bin Data In Out src Palindrome bin src OrdinalEx bin src CmdLine bin src Current Working Directory (CWD) Current location in the file system. Denoted by:. The directory from which the jvm was launched. Relative Path A path relative to the CWD. To move up:.. 4/31
Navigating the File System /home/renault/workspace CS200Ex bin Data In Out src Palindrome bin src OrdinalEx bin src CmdLine bin src Current Working Directory (CWD) Current location in the file system. Denoted by:. The directory from which the jvm was launched. Relative Path A path relative to the CWD. To move up:.. Absolute Path A path that starts at the root of the file system. Root: / 4/31
Navigating the File System /home/renault/workspace CS200Ex bin Data In Out src Palindrome bin src OrdinalEx bin src CmdLine bin src TopHat Question 2 Is./Palindrome/src an absolute or a relative path? 4/31
Navigating the File System /home/renault/workspace CS200Ex bin Data In Out src Palindrome bin src OrdinalEx bin src CmdLine bin src TopHat Question 2 Is./Palindrome/src an absolute or a relative path? TopHat Question 3 Is /home/renault/workspace/cmdline an absolute or a relative path? 4/31
Navigating the File System /home/renault/workspace CS200Ex bin Data In Out src Palindrome bin src OrdinalEx bin src CmdLine bin src TopHat Question 2 Is./Palindrome/src an absolute or a relative path? TopHat Question 3 Is /home/renault/workspace/cmdline an absolute or a relative path? TopHat Question 4 If the CWD is /home/renault/workspace/cs200ex/bin, what is the relative path to In? 4/31
Exceptions
5/31 Exceptions What is an exception? Shorthand for an exceptional event. An event that interrupts the normal flow of the program.
5/31 Exceptions What is an exception? Shorthand for an exceptional event. An event that interrupts the normal flow of the program. What causes these events? A failure of the machine where the program is running.
5/31 Exceptions What is an exception? Shorthand for an exceptional event. An event that interrupts the normal flow of the program. What causes these events? A failure of the machine where the program is running. A programming error.
5/31 Exceptions What is an exception? Shorthand for an exceptional event. An event that interrupts the normal flow of the program. What causes these events? A failure of the machine where the program is running. A programming error. A user goes off the happy path.
5/31 Exceptions What is an exception? Shorthand for an exceptional event. An event that interrupts the normal flow of the program. What causes these events? A failure of the machine where the program is running. A programming error. A user goes off the happy path. Why use exceptions? Separates error-checking from normal happy path code. Organized with try-catch-finally and throws.
6/31 Java Exception Hierarchy Object Throwable Error Exception... Runtime......
7/31 Errors Causes Errors are caused by abnormal conditions beyond the control of the programmer causing the program to fail such as hardware failures. Some Examples java.io.ioerror java.lang.outofmemoryerror java.lang.linkageerror
8/31 Java Exception Hierarchy Object Throwable Error Exception... Runtime......
9/31 Runtime Exception Causes Runtime Exceptions are typically caused by programming errors (bugs) not caught at compile time such as trying to access an out of bounds cell in an array. Some Examples java.lang.nullpointerexception java.lang.indexoutofboundsexception java.lang.arrayindexoutofboundsexception java.lang.stringindexoutofboundsexception java.lang.arithmeticexception
10/31 Java Exception Hierarchy Object Throwable Error Exception... Runtime......
10/31 Java Exception Hierarchy Object Throwable Error Exception... Unchecked Runtime......
10/31 Java Exception Hierarchy Object Throwable Error Checked Exception... Unchecked Runtime......
11/31 Unchecked vs Checked Unchecked Exception An unchecked exception is an exceptional condition that the application usually cannot anticipate or recover from. These are: Errors Runtime exceptions
11/31 Unchecked vs Checked Unchecked Exception An unchecked exception is an exceptional condition that the application usually cannot anticipate or recover from. These are: Errors Runtime exceptions Checked Exceptions All other exceptions are checked exceptions. A method must handle all checked exceptions by either: Using a try-catch block, or Throwing the exception.
12/31 TopHat Question 5 What kind of exception is java.util.inputmismatchexception? The following code compiles. When the user inputs a, the program terminates with a java.util.inputmismatchexception. import java. util. Scanner ; public class ExceptionEx1 { public static void main ( String [] arg ) { Scanner sc = new Scanner ( System. in ); int a = sc. nextint (); System. out. println (" Value is " + a);
13/31 try-catch try { trystmt1 ;... trystmtn ; catch ( AnException e) { catchstmt1 ;... catchstmtn ;
13/31 try-catch try { trystmt1 ;... trystmtn ; catch ( AnException e) { catchstmt1 ;... catchstmtn ; Control Flow Try Stmt Block AnException? No Following statements Yes AnException Catch Block
14/31 TopHat Question 6 What is the output when the user enters z? Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); System. out. println (" Value is " + a); catch ( Exception e) { System. out. print (" Catch."); System. out. print (" Done.");
15/31 Catching the Exact Exception Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); System. out. println (" Value is " + a); catch ( Exception e) { System. out. print (" Catch."); Best Practice When catching exceptions, be as precise as possible about the exception.
15/31 Catching the Exact Exception Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); System. out. println (" Value is " + a); catch ( InputMismatchException e) { System. out. print (" Input was not an integer."); Best Practice When catching exceptions, be as precise as possible about the exception.
16/31 Stack Trace Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); System. out. println (" Value is " + a); catch ( InputMismatchException e) { System. out. println (" Input was not an integer."); e. printstacktrace (); Stack Trace Prints the trace of methods calls (with line numbers) on the stack leading to the exception. Throwable has an instance method printstacktrace().
17/31 Basic try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ;
17/31 Basic try-catch-finally Basic Control Flow Try Stmt Block try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; AnException? No Finally Stmt Block Yes AnException Catch Block Following statements
18/31 TopHat Question 7 What is the output when the user enters z? Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); System. out. print (" Value is " + a + "."); catch ( InputMismatchException e) { System. out. print (" Catch."); finally { System. out. print (" Finally."); System. out. print (" Done.");
19/31 TopHat Question 8 What is the output when the user enters 2? Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); System. out. print (" Value is " + a + "."); catch ( InputMismatchException e) { System. out. print (" Catch."); finally { System. out. print (" Finally."); System. out. print (" Done.");
20/31 Multiple catch try { trystatements ; catch ( Exception1 e) { catch1statements ; catch ( Exception2 e) { catch1statements ;... catch ( ExceptionN e) {
20/31 Multiple catch Control Flow try { trystatements ; catch ( Exception1 e) { catch1statements ; catch ( Exception2 e) { catch1statements ;... catch ( ExceptionN e) { Exception1 Catch Block Try Stmt Block Caught Exception? ExceptionN Catch Block Following statements No
21/31 TopHat Question 9 What is the output when the user enters 0? Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); System. out. print (" Value is " + 10/ a + "."); catch ( InputMismatchException e) { System. out. print (" Catch Mismatch."); catch ( ArithmeticException e) { System. out. print (" Catch Div 0."); finally { System. out. print (" Finally."); System. out. print (" Done.");
22/31 Advanced try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; What if the catch block throws an exception?
22/31 Advanced try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; What if the catch block throws an exception? The finally block is still executed.
22/31 Advanced try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; What if the catch block returns? What if the catch block throws an exception? The finally block is still executed.
22/31 Advanced try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; What if the catch block returns? The finally block is still executed. What if the catch block throws an exception? The finally block is still executed.
22/31 Advanced try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; What if the catch block returns? The finally block is still executed. What if the try block returns? What if the catch block throws an exception? The finally block is still executed.
22/31 Advanced try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; What if the catch block throws an exception? The finally block is still executed. What if the catch block returns? The finally block is still executed. What if the try block returns? The finally block is still executed.
22/31 Advanced try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; What if the catch block throws an exception? The finally block is still executed. What if the catch block returns? The finally block is still executed. What if the try block returns? The finally block is still executed. What if the try block throws an uncaught exception?
22/31 Advanced try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; What if the catch block throws an exception? The finally block is still executed. What if the catch block returns? The finally block is still executed. What if the try block returns? The finally block is still executed. What if the try block throws an uncaught exception? The finally block is still executed.
23/31 TopHat Question 11 What is the output when the user enters z? Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); System. out. print (" Value is " + a + "."); return ; catch ( InputMismatchException e) { System. out. print (" Catch."); return ; finally { System. out. print (" Finally.");
24/31 Basic Throwing Exceptions Creating and Using Exceptions Constructors: Exception() Creates an Exception object. Exception(msg) Creates an Exception object containing the message msg.
24/31 Basic Throwing Exceptions Creating and Using Exceptions Constructors: Exception() Creates an Exception object. Exception(msg) Creates an Exception object containing the message msg. Some methods: printstacktrace() Prints the exception stack trace. getmessage() Returns the message associated with the exception.
24/31 Basic Throwing Exceptions Creating and Using Exceptions Constructors: Exception() Creates an Exception object. Exception(msg) Creates an Exception object containing the message msg. Some methods: printstacktrace() Prints the exception stack trace. getmessage() Returns the message associated with the exception. Throwing an Exception throw athrowable; Stops normal executions and throws an exception. E.g. throw new Exception("An exception!");
TopHat Question 12 What is the output when the user enters z? Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); if(a <= 0) throw new Exception (" Error : Val <= 0."); System. out. print (" Value is " + 10/ a + "."); catch ( InputMismatchException e) { System. out. print (" Catch Mismatch."); catch ( Exception e) { System. out. print (e. getmessage ()); finally { System. out. print (" Finally."); System. out. print (" Done."); 25/31
TopHat Question 13 What is the output when the user enters 0? Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); if(a <= 0) throw new Exception (" Error : Val <= 0."); System. out. print (" Value is " + 10/ a + "."); catch ( InputMismatchException e) { System. out. print (" Catch Mismatch."); catch ( Exception e) { System. out. print (e. getmessage ()); finally { System. out. print (" Finally."); System. out. print (" Done."); 26/31
27/31 Methods Throwing Exceptions Specifying Exceptions Thrown... somemethod(...) throws exception1,exception2,... Part of the method header. All checked exceptions must be listed. Unchecked ones are optional.
27/31 Methods Throwing Exceptions Specifying Exceptions Thrown... somemethod(...) throws exception1,exception2,... Part of the method header. All checked exceptions must be listed. Unchecked ones are optional. Throwing vs Catching A method, somemethod, that throws a checked exception is passing the exception to the caller.
27/31 Methods Throwing Exceptions Specifying Exceptions Thrown... somemethod(...) throws exception1,exception2,... Part of the method header. All checked exceptions must be listed. Unchecked ones are optional. Throwing vs Catching A method, somemethod, that throws a checked exception is passing the exception to the caller. The caller can either: Throw the exception further up the stack calls, or
27/31 Methods Throwing Exceptions Specifying Exceptions Thrown... somemethod(...) throws exception1,exception2,... Part of the method header. All checked exceptions must be listed. Unchecked ones are optional. Throwing vs Catching A method, somemethod, that throws a checked exception is passing the exception to the caller. The caller can either: Throw the exception further up the stack calls, or Put the method call to somemethod in a try block and handle the exception in a catch block.
28/31 TopHat Question 14 What is the output when the user enters 0? public static void div ( int a, int b) throws Exception { if(b == 0) throw new Exception (" Error : a is 0."); System. out. print (" Value is " + b/a + "."); public static void main ( String [] arg ) { Scanner sc = new Scanner ( System. in ); int a = sc. nextint (); try { div (10, a); catch ( Exception e) { System. out. print (e. getmessage ()); System. out. print (" Done.");
TopHat Question 15 What is the stack trace output when the program runs? 1 public class ExceptionEx11 { 2 3 public static void f() throws Exception { 4 throw new Exception (); 5 6 7 public static void main ( String [] arg ) { 8 try { 9 g (); 10 11 catch ( Exception e) { 12 e. printstacktrace (); 13 14 15 16 public static void g() throws Exception { 17 f (); 18 19 29/31
30/31 Further Reading COMP SCI 200: Programming I zybooks.com, 2015. zybook code: WISCCOMPSCI200Fall2017 Chapter 10. Exceptions
Appendix References Appendix
Appendix References References
Appendix References 31/31 Image Sources I https://brand.wisc.edu/web/logos/ http://www.zybooks.com/