CS 200 - Programming I: Exceptions€¦ · Command-Line Arguments Exceptions Passing Command-Line...

Post on 20-Jun-2020

12 views 0 download

Transcript of CS 200 - Programming I: Exceptions€¦ · Command-Line Arguments Exceptions Passing Command-Line...

CS 200 - Programming I: Exceptions

Marc Renault

Department of Computer SciencesUniversity of Wisconsin – Madison

Spring 2018TopHat Sec 3 (AM) Join Code: 427811TopHat Sec 4 (PM) Join Code: 165455

Command-Line Arguments Exceptions

Command-Line Arguments

Command-Line Arguments Exceptions

Passing Command-Line Arguments

Example: java CmdLineEx arg0 agr1 arg2

Command-Line ArgumentsArguments passed to the program when it is launched.In example: arg0, arg1, arg2

String[] argsPassed to the main method via the String[] args.In example: String[] args = {"arg0","arg1","arg2"}.

1/29

Command-Line Arguments Exceptions

Passing Command-Line Arguments

Example: java CmdLineEx arg0 agr1 arg2

Command-Line ArgumentsArguments passed to the program when it is launched.In example: arg0, arg1, arg2

String[] argsPassed to the main method via the String[] args.In example: String[] args = {"arg0","arg1","arg2"}.

1/29

Command-Line Arguments Exceptions

TopHat Question 1

What is the output when executed using the commandjava 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);

}

}

2/29

Command-Line Arguments Exceptions

Command-Line Argument Exercise

Write a program that receives from the command line both astring and action to perform (either changing to upper case orlower case). The command-line arguments are organized asfollows:

-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 behandled in any order.After parsing the arguments, the program outputs the string,having converted to upper or lower case as per thecommand-line arguments.

3/29

Command-Line Arguments Exceptions

Exceptions

Command-Line Arguments Exceptions

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.

4/29

Command-Line Arguments Exceptions

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.

4/29

Command-Line Arguments Exceptions

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.

4/29

Command-Line Arguments Exceptions

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.

4/29

Command-Line Arguments Exceptions

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.

4/29

Command-Line Arguments Exceptions

Java Exception Hierarchy

Object

Throwable

Error

...

Exception

Runtime

...

...

5/29

Command-Line Arguments Exceptions

Errors

CausesErrors are caused by abnormal conditions beyond the control ofthe programmer causing the program to fail such as hardwarefailures.

Some Examplesjava.io.IOError

java.lang.OutOfMemoryError

java.lang.LinkageError

6/29

Command-Line Arguments Exceptions

Java Exception Hierarchy

Object

Throwable

Error

...

Exception

Runtime

...

...

7/29

Command-Line Arguments Exceptions

Runtime Exception

CausesRuntime Exceptions are typically caused by programmingerrors (bugs) not caught at compile time such as trying toaccess an out of bounds cell in an array.

Some Examplesjava.lang.NullPointerExceptionjava.lang.IndexOutOfBoundsException

java.lang.ArrayIndexOutOfBoundsExceptionjava.lang.StringIndexOutOfBoundsException

java.lang.ArithmeticException

8/29

Command-Line Arguments Exceptions

Java Exception Hierarchy

Object

Throwable

Error

...

Exception

Runtime

...

...

9/29

Command-Line Arguments Exceptions

Java Exception Hierarchy

Unchecked

Object

Throwable

Error

...

Exception

Runtime

...

...

9/29

Command-Line Arguments Exceptions

Java Exception Hierarchy

Unchecked

Checked

Object

Throwable

Error

...

Exception

Runtime

...

...

9/29

Command-Line Arguments Exceptions

Unchecked vs Checked

Unchecked ExceptionAn unchecked exception is an exceptional condition that theapplication usually cannot anticipate or recover from. Theseare:

ErrorsRuntime exceptions

Checked ExceptionsAll other exceptions are checked exceptions. A method musthandle all checked exceptions by either:

Using a try-catch block, orThrowing the exception.

10/29

Command-Line Arguments Exceptions

Unchecked vs Checked

Unchecked ExceptionAn unchecked exception is an exceptional condition that theapplication usually cannot anticipate or recover from. Theseare:

ErrorsRuntime exceptions

Checked ExceptionsAll other exceptions are checked exceptions. A method musthandle all checked exceptions by either:

Using a try-catch block, orThrowing the exception.

10/29

Command-Line Arguments Exceptions

TopHat Question 2What kind of exception isjava.util.InputMismatchException?The following code compiles. When the user inputs “a”, theprogram terminates with ajava.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);

}

}

11/29

Command-Line Arguments Exceptions

try-catch

try {tryStmt1;...tryStmtN;

}catch (AnException e) {

catchStmt1;...catchStmtN;

}

Control Flow

Try Stmt Block

AnException?

AnExceptionCatch Block

Followingstatements

Yes

No

12/29

Command-Line Arguments Exceptions

try-catch

try {tryStmt1;...tryStmtN;

}catch (AnException e) {

catchStmt1;...catchStmtN;

}

Control Flow

Try Stmt Block

AnException?

AnExceptionCatch Block

Followingstatements

Yes

No

12/29

Command-Line Arguments Exceptions

TopHat Question 3

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.");

13/29

Command-Line Arguments Exceptions

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 PracticeWhen catching exceptions, be as precise as possible about theexception.

14/29

Command-Line Arguments Exceptions

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 PracticeWhen catching exceptions, be as precise as possible about theexception.

14/29

Command-Line Arguments Exceptions

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 TracePrints the trace of methods calls (with line numbers) on thestack leading to the exception.Throwable has an instance method printStackTrace().

15/29

Command-Line Arguments Exceptions

Basic try-catch-finally

try {tryStatements;

}catch (AnException e) {

catchStatements;}finally {

finallyStatements;}

Basic Control Flow

Try Stmt Block

AnException?

AnExceptionCatch Block

Finally Stmt Block

Followingstatements

Yes

No

16/29

Command-Line Arguments Exceptions

Basic try-catch-finally

try {tryStatements;

}catch (AnException e) {

catchStatements;}finally {

finallyStatements;}

Basic Control Flow

Try Stmt Block

AnException?

AnExceptionCatch Block

Finally Stmt Block

Followingstatements

Yes

No

16/29

Command-Line Arguments Exceptions

TopHat Question 4

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.");

17/29

Command-Line Arguments Exceptions

TopHat Question 5

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.");

18/29

Command-Line Arguments Exceptions

Multiple catch

try {tryStatements;

}catch (Exception1 e) {

catch1Statements;}catch (Exception2 e) {

catch1Statements;}...catch (ExceptionN e) {

}

Control Flow

Try Stmt Block

CaughtException?

Exception1Catch Block

ExceptionNCatch Block

Followingstatements

No

19/29

Command-Line Arguments Exceptions

Multiple catch

try {tryStatements;

}catch (Exception1 e) {

catch1Statements;}catch (Exception2 e) {

catch1Statements;}...catch (ExceptionN e) {

}

Control Flow

Try Stmt Block

CaughtException?

Exception1Catch Block

ExceptionNCatch Block

Followingstatements

No

19/29

Command-Line Arguments Exceptions

TopHat Question 6What 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.");

20/29

Command-Line Arguments Exceptions

Advanced try-catch-finally

try {tryStatements;

}catch (AnException e) {

catchStatements;}finally {

finallyStatements;}

What if the catch blockthrows an exception?

The finally block is stillexecuted.

What if the catch blockreturns?The finally block is stillexecuted.

What if the try blockreturns?The finally block is stillexecuted.

What if the try block throwsan uncaught exception?The finally block is stillexecuted.

21/29

Command-Line Arguments Exceptions

Advanced try-catch-finally

try {tryStatements;

}catch (AnException e) {

catchStatements;}finally {

finallyStatements;}

What if the catch blockthrows an exception?The finally block is stillexecuted.

What if the catch blockreturns?The finally block is stillexecuted.

What if the try blockreturns?The finally block is stillexecuted.

What if the try block throwsan uncaught exception?The finally block is stillexecuted.

21/29

Command-Line Arguments Exceptions

Advanced try-catch-finally

try {tryStatements;

}catch (AnException e) {

catchStatements;}finally {

finallyStatements;}

What if the catch blockthrows an exception?The finally block is stillexecuted.

What if the catch blockreturns?

The finally block is stillexecuted.

What if the try blockreturns?The finally block is stillexecuted.

What if the try block throwsan uncaught exception?The finally block is stillexecuted.

21/29

Command-Line Arguments Exceptions

Advanced try-catch-finally

try {tryStatements;

}catch (AnException e) {

catchStatements;}finally {

finallyStatements;}

What if the catch blockthrows an exception?The finally block is stillexecuted.

What if the catch blockreturns?The finally block is stillexecuted.

What if the try blockreturns?The finally block is stillexecuted.

What if the try block throwsan uncaught exception?The finally block is stillexecuted.

21/29

Command-Line Arguments Exceptions

Advanced try-catch-finally

try {tryStatements;

}catch (AnException e) {

catchStatements;}finally {

finallyStatements;}

What if the catch blockthrows an exception?The finally block is stillexecuted.

What if the catch blockreturns?The finally block is stillexecuted.

What if the try blockreturns?

The finally block is stillexecuted.

What if the try block throwsan uncaught exception?The finally block is stillexecuted.

21/29

Command-Line Arguments Exceptions

Advanced try-catch-finally

try {tryStatements;

}catch (AnException e) {

catchStatements;}finally {

finallyStatements;}

What if the catch blockthrows an exception?The finally block is stillexecuted.

What if the catch blockreturns?The finally block is stillexecuted.

What if the try blockreturns?The finally block is stillexecuted.

What if the try block throwsan uncaught exception?The finally block is stillexecuted.

21/29

Command-Line Arguments Exceptions

Advanced try-catch-finally

try {tryStatements;

}catch (AnException e) {

catchStatements;}finally {

finallyStatements;}

What if the catch blockthrows an exception?The finally block is stillexecuted.

What if the catch blockreturns?The finally block is stillexecuted.

What if the try blockreturns?The finally block is stillexecuted.

What if the try block throwsan uncaught exception?

The finally block is stillexecuted.

21/29

Command-Line Arguments Exceptions

Advanced try-catch-finally

try {tryStatements;

}catch (AnException e) {

catchStatements;}finally {

finallyStatements;}

What if the catch blockthrows an exception?The finally block is stillexecuted.

What if the catch blockreturns?The finally block is stillexecuted.

What if the try blockreturns?The finally block is stillexecuted.

What if the try block throwsan uncaught exception?The finally block is stillexecuted.

21/29

Command-Line Arguments Exceptions

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 + ".");return;

}catch(InputMismatchException e) {

System.out.print("Catch.");return;

}finally {

System.out.print("Finally.");}

22/29

Command-Line Arguments Exceptions

Basic Throwing ExceptionsCreating and Using Exceptions

Constructors:Exception() – Creates an Exception object.Exception(msg) – Creates an Exception object containingthe message msg.

Some methods:printStackTrace() – Prints the exception stack trace.getMessage() – Returns the message associated with theexception.

Throwing an Exceptionthrow aThrowable;

Stops normal executions and throws an exception.E.g.throw new Exception("An exception!");

23/29

Command-Line Arguments Exceptions

Basic Throwing ExceptionsCreating and Using Exceptions

Constructors:Exception() – Creates an Exception object.Exception(msg) – Creates an Exception object containingthe message msg.

Some methods:printStackTrace() – Prints the exception stack trace.getMessage() – Returns the message associated with theexception.

Throwing an Exceptionthrow aThrowable;

Stops normal executions and throws an exception.E.g.throw new Exception("An exception!");

23/29

Command-Line Arguments Exceptions

Basic Throwing ExceptionsCreating and Using Exceptions

Constructors:Exception() – Creates an Exception object.Exception(msg) – Creates an Exception object containingthe message msg.

Some methods:printStackTrace() – Prints the exception stack trace.getMessage() – Returns the message associated with theexception.

Throwing an Exceptionthrow aThrowable;

Stops normal executions and throws an exception.E.g.throw new Exception("An exception!");

23/29

Command-Line Arguments Exceptions

TopHat Question 8What 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.");

24/29

Command-Line Arguments Exceptions

TopHat Question 9What 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.");

25/29

Command-Line Arguments Exceptions

Methods Throwing ExceptionsSpecifying Exceptions Thrown... someMethod(...) throws exception1,exception2,...

Part of the method header.All checked exceptions must be listed.Unchecked ones are optional.

Throwing vs CatchingA method, someMethod, that throws a checked exception ispassing the exception to the caller.The caller can either:

Throw the exception further up the stack calls, orPut the method call to someMethod in a try block andhandle the exception in a catch block.

26/29

Command-Line Arguments Exceptions

Methods Throwing ExceptionsSpecifying Exceptions Thrown... someMethod(...) throws exception1,exception2,...

Part of the method header.All checked exceptions must be listed.Unchecked ones are optional.

Throwing vs CatchingA method, someMethod, that throws a checked exception ispassing the exception to the caller.

The caller can either:Throw the exception further up the stack calls, orPut the method call to someMethod in a try block andhandle the exception in a catch block.

26/29

Command-Line Arguments Exceptions

Methods Throwing ExceptionsSpecifying Exceptions Thrown... someMethod(...) throws exception1,exception2,...

Part of the method header.All checked exceptions must be listed.Unchecked ones are optional.

Throwing vs CatchingA method, someMethod, that throws a checked exception ispassing 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 andhandle the exception in a catch block.

26/29

Command-Line Arguments Exceptions

Methods Throwing ExceptionsSpecifying Exceptions Thrown... someMethod(...) throws exception1,exception2,...

Part of the method header.All checked exceptions must be listed.Unchecked ones are optional.

Throwing vs CatchingA method, someMethod, that throws a checked exception ispassing the exception to the caller.The caller can either:

Throw the exception further up the stack calls, orPut the method call to someMethod in a try block andhandle the exception in a catch block.

26/29

Command-Line Arguments Exceptions

TopHat Question 10What 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.");

}

27/29

Command-Line Arguments Exceptions

TopHat Question 11What is the stack trace output when the program runs?

1 public class ExceptionEx11 {23 public static void f() throws Exception {4 throw new Exception ();5 }67 public static void main(String [] arg) {8 try {9 g();

10 }11 catch(Exception e) {12 e.printStackTrace ();13 }14 }1516 public static void g() throws Exception {17 f();18 }1920 }

28/29

Command-Line Arguments Exceptions

Further Reading

COMP SCI 200: Programming IzyBooks.com, 2015.zyBook code:WISCCOMPSCI200Spring2018

Chapter 10. Exceptions

29/29

Appendix References

Appendix

Appendix References

References

Appendix References

Image Sources I

https://brand.wisc.edu/web/logos/

http://www.zybooks.com/

30/29