10
CS 1302 – Lab 05 This is a tutorial on exceptions. There are 7 stages to complete this lab: Stag e Title Text Reference 1 Understanding Exceptions and try/catch 12.1-12.2 2 try/catch Example 12.1-12.2 3 Throwing an Exception 12.4 To make this document easier to read, it is recommended that you turn off spell checking in Word: 1. Choose: File, Option, Proofing 2. At the very bottom, check: “Hide spelling errors…” and “Hide grammar errors…” Stage 1 -Understanding Exceptions and try/catch In this stage you will learn about exceptions and using the try/catch block. You will not write any code in this stage. 1. Read (no action required) – When your code tries to do something illegal (e.g. divide by zero, call a method on an object that is null) a run-time error occurs and an Exception is thrown as shown in the class diagram below. If this exception is not caught (handled) then the program terminates. Java defines the Exception class. Subclasses (e.g. ArithmeticException, etc. ) correspond to specific types of errors that can occur in the program. For example, if you try to divide by zero, an ArithmeticException occurs. Similarly, if you try to access a position in a string that doesn’t exist, a StringIndexOutOfBoundsException occurs. 1

mypages.valdosta.edu€¦  · Web viewand the program terminates. The Console window shows the exception that was thrown and then the sequence of statements that lead to the exception

  • Upload
    others

  • View
    8

  • Download
    0

Embed Size (px)

Citation preview

Page 1: mypages.valdosta.edu€¦  · Web viewand the program terminates. The Console window shows the exception that was thrown and then the sequence of statements that lead to the exception

CS 1302 – Lab 05

This is a tutorial on exceptions. There are 7 stages to complete this lab:

Stage Title Text Reference1 Understanding Exceptions and try/catch 12.1-12.22 try/catch Example 12.1-12.23 Throwing an Exception 12.4

To make this document easier to read, it is recommended that you turn off spell checking in Word:

1. Choose: File, Option, Proofing2. At the very bottom, check: “Hide spelling errors…” and “Hide grammar errors…”

Stage 1 - Understanding Exceptions and try/catch

In this stage you will learn about exceptions and using the try/catch block. You will not write any code in this stage.

1. Read (no action required) – When your code tries to do something illegal (e.g. divide by zero, call a method on an object that is null) a run-time error occurs and an Exception is thrown as shown in the class diagram below. If this exception is not caught (handled) then the program terminates. Java defines the Exception class. Subclasses (e.g. ArithmeticException, etc.) correspond to specific types of errors that can occur in the program. For example, if you try to divide by zero, an ArithmeticException occurs. Similarly, if you try to access a position in a string that doesn’t exist, a StringIndexOutOfBoundsException occurs.

1

Page 2: mypages.valdosta.edu€¦  · Web viewand the program terminates. The Console window shows the exception that was thrown and then the sequence of statements that lead to the exception

2. Read (no action required) – For example, consider the code below which calls inverse(0) and the inverse method attempts to divide 1 by 0 which results in an ArithmeticException and the program terminates. The Console window shows the exception that was thrown and then the sequence of statements that lead to the exception. For example, as shown in the figure below, line 11 was where the exception was thrown and line 7 was the call to the method.

3. Read (no action required) – Java defines a try/catch block that is used to catch exceptions so that the code does not terminate when an exception is thrown. As shown below, you put code that might fail in the try block and code to recover from the failure in the catch block.

try {// Code that may fail

}catch(Exception e) {

// Code to recover from failure}

2

Page 3: mypages.valdosta.edu€¦  · Web viewand the program terminates. The Console window shows the exception that was thrown and then the sequence of statements that lead to the exception

4. Read (no action required) – Consider the code shown below on the right and the description of the numbered steps on the left. This code illustrates the use of a try/catch block to catch an exception.

Step Description1 inverse is called with the

argument 02 An attempt is made on

line 16 to divide by 03 An ArithmeticException is

thrown and is caught on line 10

4 A message is printed

5. Read (no action required) – Consider the code shown below on the right and the description of the numbered steps on the left. This is the same code as above (except that x=4), however no exception is thrown. Notice that the catch block is not activated when no exception is thrown.

Step Description1 inverse is called with the

argument 42 At line 16, 1 is divided by

4.3 The value (0.25) is

returned.4 The value is printed

3

Page 4: mypages.valdosta.edu€¦  · Web viewand the program terminates. The Console window shows the exception that was thrown and then the sequence of statements that lead to the exception

Stage 2 - try/catch Example

In this stage we provide a simple example of using try/catch.

6. Do the following:

a. Establish a Workspace – Create a folder on your drive where you will put your lab or use an existing one.b. Run Eclipse – As the program begins to run, it will ask you to navigate to the Workspace you want to use.c. Create a Project – Create a Java project with the name, lab05_lastNameFirstInitial, e.g. lab05_gibsond.

7. Do the following:

a. Create a package named exception_examples1.b. Create a class named Example1 and replace everything in the class (except the package statement at the

top) with:

public class Example1 {

public static void main(String[] args) {char c = getCharAt("help", 8);System.out.println( c );

}

public static char getCharAt(String msg, int pos) {return msg.charAt(pos);

}}

c. Run and observe the output.

8. Add these lines to the beginning of main:

System.out.println("Answers:");System.out.println("a. ??? ");System.out.println("b. ??? ");System.out.println("c. ??? ");System.out.println("d. ??? ");

Answer the four questions below by replacing the “???”’s in the code above with your answers.

a. What is the class of the exception that is thrown?b. What caused this exception to be thrown (e.g. what was the programming error)?c. The output is similar to below. What do the last two links show?

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 8

at java.lang.String.charAt(Unknown Source)at lab4.Problem1.getCharAt(Problem1.java:11)at lab4.Problem1.main(Problem1.java:6)

4

Page 5: mypages.valdosta.edu€¦  · Web viewand the program terminates. The Console window shows the exception that was thrown and then the sequence of statements that lead to the exception

d. Does this line in main:

System.out.println( c );

get executed? Rerun or use the debugger if necessary. Why or why not?

9. Do the following:

a. Create a class named Example2 and replace everything in the class (except the package statement at the top) with:

public class Example2 {

public static void main(String[] args) {char c;try {

c = getCharAt("help", 8);System.out.println("Got the answer!");

}catch(RuntimeException e) {

System.out.println("Exception:\n " + e);c = '*';

}System.out.println( "Character is: " + c );

}

public static char getCharAt(String msg, int pos) {return msg.charAt(pos);

}}

b. Run the code and verify the output.

c. Set a breakpoint on line 8:

c = getCharAt("help", 8);

d. Start the debugger and step into the code (F5). Carefully trace the code execution. Note the following:

i. An exception is thrown and after the catch block has finished, line 15 is executed:

System.out.println( "Character is: " + c );

This illustrates that program execution resumes with the statement immediately following a catch block (unless the exception is rethrown, we will discuss this later).

ii. Line 9 is never executed:

System.out.println("Got the answer!");

5

Page 6: mypages.valdosta.edu€¦  · Web viewand the program terminates. The Console window shows the exception that was thrown and then the sequence of statements that lead to the exception

10. Do the following:

a. Make the changes shown on the right to your code. You will get a compile error, we discuss that next.

b. Add these lines to the beginning of main:

System.out.println("Answers:");System.out.println("i. ??? ");System.out.println("ii. ??? ");System.out.println("iii. ??? ");

Answer the questions below by replacing the “???”’s in the code above with your answers.

i. Why doesn’t the code compile?ii. True or False: A variable declared inside a try block can only be used inside the try block.

iii. Fill in the blank: Suppose a variable is used inside a try block. If you need to use that variable outside the try/catch block then it must be declared _____ (inside or outside) the try/catch block.

c. Reverse the changes you made in step a immediately above (so the code is in its original state and compiles). Run, and verify that your answers appear.

Stage 3 - Throwing an Exception

In this stage we show how to explicitly throw an exception

11. (Read, no action required) – Java allows the programmer to throw an exception. For example, suppose we have a Dog class whose constructor requires a name as an argument and that we require that the name be at least 2 characters long. One way to enforce this to have the Dog constructor throw an exception if the name is not 2 or more characters long. For example:

throw new IllegalArgumentException(“…description…”);

or

throw new RuntimeException(“…description…”);

Which type of exception should you throw? In the example above we said the Dog constructor accepted a name parameter that was subject to constraints. Thus, it makes sense to throw an IllegalArgumentException which is a subclass of RuntimeException. In other cases, the condition might not fit neatly into one of Java’s RuntimeException subclasses so we might just throw a RuntimeException. Alternately, we can create our own custom exception class that extends RuntimeException. We will consider this later in this lab.

6

Page 7: mypages.valdosta.edu€¦  · Web viewand the program terminates. The Console window shows the exception that was thrown and then the sequence of statements that lead to the exception

12. Do the following:

a. Create a class named Dog and replace everything in the class (except the package statement at the top) with:

public class Dog {private String name;public Dog(String name) {

if( name.length() < 2) {throw new IllegalArgumentException("Name length must be 2 or

more");}else {

this.name = name;}

}

@Overridepublic String toString() {

return "Dog's name is: " + name;}

public static void main(String[] args) {Dog d;try{

d = new Dog("a");System.out.println(d);

}catch(RuntimeException e){

System.out.println(e);}System.out.println("Program over!");

}}

b. Study the code above carefully. Then, run and verify the output.

c. Change the argument “a” in main to a name that is 2 or more characters long. Then, run and verify the output.

You are done!

7