Java Lecture 09 - laulima.hawaii.edu

63
Exception Handling ICS 111 Ed Meyer

Transcript of Java Lecture 09 - laulima.hawaii.edu

Exception HandlingICS 111

Ed Meyer

Today

• Exceptions• How to handle exceptions try/catch

2

What is an Exception?

• An event that disrupts program execution• Exceptions may Prevent a program from compiling (Checked) Cause your program to crash (Unchecked)

3

What is an Exception?

• An event that disrupts program execution• Exceptions may Prevent a program from compiling (Checked) Cause your program to crash (Unchecked)

• Crashing code is okay, but make sure you learn from them Test your code by crashing your program on purpose An assignment may have many Example Outputs

4

Care about Exceptions

• Anticipate the possibility of exceptions happening Even if you create very descriptive instructions and feedback to the

user, they don't always read it

• Use exception handling

5

The ArithmeticException Exception

• An error during any kind of arithmetic operation For instance, integer division by zero

• Exampleint divZero = 5 / 0; The above is syntactically correct, but will crash at runtime

6

Anticipating an Exception

• Division by zero may happen when you have the user enter numeric information The user may enter a zero

• The result of arithmetic may result in a division by zero

7

----jGRASP exec: java BuggahNoListenPlease enter a non-zero integer: 0

Divide by Zero (Example)int input1 = 15;

int input2 = 7;

int input3 = 8;

int dividend = 78;

int result = 0;

result = dividend / (input1 – input2 – input3);

8

Divide by Zero (Example)int input1 = 15;

int input2 = 7;

int input3 = 8;

int dividend = 78;

int result = 0;

result = dividend / (input1 – input2 – input3);

9

15 – 7 – 8 = 0

When you run the code...

10

----jGRASP exec: java TryDivByZeroException in thread "main" java.lang.ArithmeticException: / by zeroat TryDivByZero.main(TryDivByZero.java:11)

----jGRASP wedge2: exit code for process is 1.----jGRASP: operation complete.

When you run the code...

11

----jGRASP exec: java TryDivByZeroException in thread "main" java.lang.ArithmeticException: / by zeroat TryDivByZero.main(TryDivByZero.java:11)

----jGRASP wedge2: exit code for process is 1.----jGRASP: operation complete.

Handling Exceptions

• Use try and catch In Java, when an exception happens, the exception is "thrown" To handle the exception, it is "caught"

12

try/catch Syntaxtry {

// Risky, exception throwing, code goes here

// Any code that depends on risky code

}

catch (NameOfException exceptionVariable) {

// When the exception happens the code in here executes.

// Notify the user why and how to correct the problem!

}

// After an exception is caught, the program

// continues execution after the catch

13

The try Block

• Contains risky code that will throw an exception May also contain code that is dependent on/related to the risky code

• Immediately after a try block, there must be a catch block• Code in the try block is indented!

try {

// Risky, exception throwing, code goes here

// Any code that depends on risky code

}

14

The catch block

• Contains code that executes when the exception happens• You need to know the exception you are trying to catch• Placed immediately after a try block• Code in the catch block is indented!

catch (NameOfException exceptionVariable) {

// When the exception happens the code in here executes.

// Notify the user why and how to correct the problem!

}

15

The catch block

• How do you know the exception that was thrown? Java tells you when your program crashes

16

----jGRASP exec: java TryDivByZeroException in thread "main" java.lang.ArithmeticException: / by zeroat TryDivByZero.main(TryDivByZero.java:11)

----jGRASP wedge2: exit code for process is 1.----jGRASP: operation complete.

The catch block

• How do you know the exception that was thrown? Java tells you when your program crashes

17

----jGRASP exec: java TryDivByZeroException in thread "main" java.lang.ArithmeticException: / by zeroat TryDivByZero.main(TryDivByZero.java:11)

----jGRASP wedge2: exit code for process is 1.----jGRASP: operation complete.

Writing the catch Block

• Take the catch block syntax:

catch (NameOfException exceptionVariable) {

}

18

Writing the catch Block

• Replace the NameOfException and exceptionVariable:

catch (java.lang.ArithmeticException ae) {

}

19

Writing the catch Block

• Replace the NameOfException and exceptionVariable:

catch (java.lang.ArithmeticException ae) {

}

20

Writing the catch Block

• Replace the NameOfException and exceptionVariable:

catch (java.lang.ArithmeticException ae) {

}

21

The name is something we choose. It is how to reference the exception in the block.

In ICS 111, the name isn't important because we will be creating our own message.

Shortening the Exception

• We have a catch block that looks like this:

catch (java.lang.ArithmeticException ae) {

}

22

Shortening the Exception

• We have a catch block that looks like this:

catch (java.lang.ArithmeticException ae) {

}

• BUT WAIT! java.lang is already imported by default, so...

23

Shortening the Exception

• We have a catch block that looks like this:

catch (java.lang.ArithmeticException ae) {

}

• BUT WAIT! java.lang is already imported by default, so...

catch (ArithmeticException ae) {

}

24

Divide by Zero (Example)int input1 = 15;int input2 = 7;int input3 = 8;int dividend = 78;int result = 0;

try {result = dividend / (input1 – input2 – input3);

}catch (ArithmeticException ae) {System.out.println("Error: Trying to divide by 0.");

}

25

Input Exceptions

26

Exceptions when using the Scanner

• Occur when user enters something in an incorrect type• You will need to anticipate the types of errors the user can

make

27

Ask the user for AgeScanner reader = new Scanner(System.in);

int inputAge = 0;

System.out.print("Enter your age: ");

inputAge = reader.nextInt();

System.out.printf("Your age is: %d%n", inputAge);

28

Ask the user for AgeScanner reader = new Scanner(System.in);

int inputAge = 0;

System.out.print("Enter your age: ");

inputAge = reader.nextInt();

System.out.printf("Your age is: %d%n", inputAge);

29

So what happens?

30

MM«M ----jGRASP exec: java NoAskMyAge¼¼§ Enter your age: NO§ Exception in thread "main" java.util.InputMismatchException§ at java.base/java.util.Scanner.throwFor(Scanner.java:939)§ at java.base/java.util.Scanner.next(Scanner.java:1594)§ at java.base/java.util.Scanner.nextInt(Scanner.java:2258)§ at java.base/java.util.Scanner.nextInt(Scanner.java:2212)§ at NoAskMyAge.main(NoAskMyAge.java:8)§§ ----jGRASP wedge2: exit code for process is 1.

MM©M ----jGRASP: operation complete.

So what happens?

31

MM«M ----jGRASP exec: java NoAskMyAge¼¼§ Enter your age: NO§ Exception in thread "main" java.util.InputMismatchException§ at java.base/java.util.Scanner.throwFor(Scanner.java:939)§ at java.base/java.util.Scanner.next(Scanner.java:1594)§ at java.base/java.util.Scanner.nextInt(Scanner.java:2258)§ at java.base/java.util.Scanner.nextInt(Scanner.java:2212)§ at NoAskMyAge.main(NoAskMyAge.java:8)§§ ----jGRASP wedge2: exit code for process is 1.

MM©M ----jGRASP: operation complete.

Identify the Exception that was Thrown

32

MM«M ----jGRASP exec: java NoAskMyAge¼¼§ Enter your age: NO§ Exception in thread "main" java.util.InputMismatchException§ at java.base/java.util.Scanner.throwFor(Scanner.java:939)§ at java.base/java.util.Scanner.next(Scanner.java:1594)§ at java.base/java.util.Scanner.nextInt(Scanner.java:2258)§ at java.base/java.util.Scanner.nextInt(Scanner.java:2212)§ at NoAskMyAge.main(NoAskMyAge.java:8)§§ ----jGRASP wedge2: exit code for process is 1.

MM©M ----jGRASP: operation complete.

Identify the Exception that was Thrown

33

MM«M ----jGRASP exec: java NoAskMyAge¼¼§ Enter your age: NO§ Exception in thread "main" java.util.InputMismatchException§ at java.base/java.util.Scanner.throwFor(Scanner.java:939)§ at java.base/java.util.Scanner.next(Scanner.java:1594)§ at java.base/java.util.Scanner.nextInt(Scanner.java:2258)§ at java.base/java.util.Scanner.nextInt(Scanner.java:2212)§ at NoAskMyAge.main(NoAskMyAge.java:8)§§ ----jGRASP wedge2: exit code for process is 1.

MM©M ----jGRASP: operation complete.

Java API Full Method Description

• Contains a Throws section Indicates if the method will throw an exception

34

Identify where the Exception was Thrown

35

MM«M ----jGRASP exec: java NoAskMyAge¼¼§ Enter your age: NO§ Exception in thread "main" java.util.InputMismatchException§ at java.base/java.util.Scanner.throwFor(Scanner.java:939)§ at java.base/java.util.Scanner.next(Scanner.java:1594)§ at java.base/java.util.Scanner.nextInt(Scanner.java:2258)§ at java.base/java.util.Scanner.nextInt(Scanner.java:2212)§ at NoAskMyAge.main(NoAskMyAge.java:8)§§ ----jGRASP wedge2: exit code for process is 1.

MM©M ----jGRASP: operation complete.The last line indicates where the

exception happened.

Line 8 of NoAskMyAge.java

Setup the try-catch BlocksScanner reader = new Scanner(System.in);

int inputAge = 0;

System.out.print("Enter your age: ");

inputAge = reader.nextInt();

System.out.printf("Your age is: %d%n", inputAge);

36

Identify the risky code.Put risky code in try.

Setup the try-catch BlocksScanner reader = new Scanner(System.in);int inputAge = 0;

try {System.out.print("Enter your age: ");inputAge = reader.nextInt();

}catch (java.util.InputMismatchException ie) {System.out.println("Error: Integer not entered.");

}

System.out.printf("Your age is: %d%n", inputAge);

37

Test it Out!

38

MM«M ----jGRASP exec: java NoAskMyAge¼¼§ Enter your age: NO§ Error: Integer not entered.§ Your age is: 0§

MM©M ----jGRASP: operation complete.

Program Continues ExecutionScanner reader = new Scanner(System.in);int inputAge = 0;

try {System.out.print("Enter your age: ");inputAge = reader.nextInt();

}catch (java.util.InputMismatchException ie) {System.out.println("Error: Integer not entered.");

}

System.out.printf("Your age is: %d%n", inputAge);

39

Move Code that is Dependent on RiskyScanner reader = new Scanner(System.in);int inputAge = 0;

try {System.out.print("Enter your age: ");inputAge = reader.nextInt();

System.out.printf("Your age is: %d%n", inputAge);}catch (java.util.InputMismatchException ie) {System.out.println("Error: Integer not entered.");

}

40

Execution Jumps to the catchScanner reader = new Scanner(System.in);int inputAge = 0;

try {System.out.print("Enter your age: ");inputAge = reader.nextInt();

System.out.printf("Your age is: %d%n", inputAge);}catch (java.util.InputMismatchException ie) {System.out.println("Error: Integer not entered.");

}

41

When the nextInt method throws the InputMismatchException on this line, execution jumps to a matching catch block.

The rest of the try is ignoredScanner reader = new Scanner(System.in);int inputAge = 0;

try {System.out.print("Enter your age: ");inputAge = reader.nextInt();

System.out.printf("Your age is: %d%n", inputAge);}catch (java.util.InputMismatchException ie) {System.out.println("Error: Integer not entered.");

}

42

The remaining code in the try after that line, is ignored, does not execute.

Test it Out Again!

43

MM«M ----jGRASP exec: java NoAskMyAge¼¼§ Enter your age: NO§ Error: Integer not entered.§

MM©M ----jGRASP: operation complete.

Importing Exceptions

• When you know the exception you are handling, you can import them at the top

• After importing, you can reference the name without the package hierarchy

• Example:import java.util.Scanner;import java.util.InputMismatchException;

44

Shortened Name in the catchimport java.util.Scanner;import java.util.InputMismatchException;

...

catch (InputMismatchException ie) {

System.out.println("Error: Integer not entered.");

}

45

Importing an entire package

• You may be tempted to do this:import java.util.*; That essentially tells Java that you may use everything in the util

package.

46

Importing an entire package

• You may be tempted to do this:import java.util.*; That essentially tells Java that you may use everything in the util

package.

• Importing specific classes signals what you will be using from the package.

• Rule of thumb: Import entire package if using more than 5 classes from it.

47

The Scanner nextInt() Method

• Retrieves input as an integer• Throws InputMismatchException if the input is not an integer

48

The Scanner nextDouble() Method

• Retrieves input as a double• Throws InputMismatchException if the input is not a number

• This method will not crash if the input is an integer. Why?

49

The Scanner nextDouble() Method

• Retrieves input as a double• Throws InputMismatchException if the input is not a number

• This method will not crash if the input is an integer. Why? The integer will get widened! Whoo!

50

The Scanner nextLine() Method

• Retrieves an entire line of input as a String• InputMismatchException is NOT thrown at all Strings are characters, which can be numbers, letters, symbols, or

empty string.

51

The Scanner nextLine() Method

• Retrieves an entire line of input as a String• InputMismatchException is NOT thrown at all Strings are characters, which can be numbers, letters, symbols, or

empty string.

• Throws NoSuchElementException when reading a file and there is no

line to read

52

The Scanner next() Method

• Retrieves a word of input as a String Up to a space or newline

• InputMismatchException is NOT thrown at all Strings are characters, which can be numbers, letters, symbols, or

empty string.

• Throws NoSuchElementException when reading a file and there is no

word to read

53

Handling String Input

• String input cannot be controlled to be meaningful• To be sure that string makes sense other techniques will be

used Check length Trim Regular expression

54

The Exception Exception

• This exception can catch any exception that is thrown• DO NOT DO THIS! (In this class)• For demonstration only, this is what catching Exception

looks like

catch (Exception e) {

}

55

The Exception Exception

• DO NOT DO THIS! (In this class) Catching Exception can hide potential bugs that you as the

programmer do not know about.

• Handle all known exceptions and address unknown exceptions as they come up.

56

try Block

• Should contain AT LEAST ONE risky statement inside• After a try block, there must be a catch block

57

try {

}

catch Block

• What to do when the exception is thrown?• If more than one exception may occur in the try, you may have multiple

catch blocks, but still only one try block The order of the catch blocks does not matter, Java goes through each catch and

tries to find a match for the exception that was thrown.

58

try {

}catch ( ) {

}

try {

}catch ( ) {

}catch ( ) {

}

The finally Block

• Placed after all catch blocks• Used for code clean up Resetting variables Closing files

• This is an optional block• Executes after the try exits or a catch exits

59

try/catch/finally Syntaxtry {

// Risky code: exception throwing code goes here

// Any code that depends on risky code

}

catch (NameOfException exceptionVariable) {

// When the exception happens the code here will execute.

// Print a message!

}

finally {

// Code here will execute when the try or a catch block exits

}

60

try/catch/finally Flow

No exception was thrown1. try

2. finally

An exception was thrown and caught1. try

2. catch

3. finally

61

try/catch/finally Flow

No exception was thrown1. try

2. finally

An exception was thrown and caught1. try

2. catch

3. finally

62

An exception was thrown and not caught1. try

2. Program crashes

Let's do an example!

OutputLetter.java