Prac04-Exceptions 17-08-06 PDF

Title Prac04-Exceptions 17-08-06
Course Intermediate Object-Oriented Programming
Institution La Trobe University
Pages 8
File Size 233.9 KB
File Type PDF
Total Downloads 137
Total Views 743

Summary

CSE1IOO/CSE4IOO – Practice Class 4 (Week 5) Exception Handling Some Selected Exception Classes Examples of methods that throw exceptions Scanner public int nextInt()throws: InputMismatchException - if the next token does not match the Integer regular expression, or is out of range NoSuchElementExcep...


Description

CSE1IOO/CSE4IOO – Practice Class 4 (Week 5) Exception Handling Some Selected Exception Classes

Examples of methods that throw exceptions Scanner public int nextInt()throws: InputMismatchException - if the next token does not match the Integer regular expression, or is out of range NoSuchElementException - if input is exhausted IllegalStateException - if this scanner is closed

Integer public static int parseInt(String s) throws: NumberFormatException - if the string does not contain a parsable integer.

PrintWriter public PrintWriter(File file) throws: FileNotFoundException - If the given file object does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file SecurityException - If a security manager is present and checkWrite(file.getPath()) denies write access to the file

1

Question 1 – Checked and unchecked exceptions import java.io.*; import java.util.*; public class Q1 { public static void main(String [] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter 2 integers: "); int a = keyboard.nextInt(); int b = keyboard.nextInt(); int c = a/b; System.out.println("c: " + c); System.out.println(“Bye!”); } }

The above program compiles successfully. And when run, it can throw an exception with the message ArithmeticException: / by zero.

a)

Is ArithmeticException a checked exception or an unchecked exception? How can you tell?

b)

ArithmeticException is a subclass of RuntimeException. True or false?

c)

ArithmeticException is a subclass of Exception. True or false?

d)

Suppose we want to modify the program so that the last statement (System.out.println(“Bye!”) will always be executed. Which of the following programs will meet this requirement? And why?

(i) import java.io.*; import java.util.*; public class Q1 { public static void main(String [] args) { try { Scanner keyboard = new Scanner(System.in); System.out.print("Enter 2 integers: "); int a = keyboard.nextInt(); int b = keyboard.nextInt(); int c = a/b; System.out.println("c: " + c); } catch(ArithmeticException e){} System.out.println(“Bye!”); }

2

(ii) import java.io.*; import java.util.*; public class Q1 { public static void main(String [] args) { try { Scanner keyboard = new Scanner(System.in); System.out.print("Enter 2 integers: "); int a = keyboard.nextInt(); int b = keyboard.nextInt(); int c = a/b; System.out.println("c: " + c); } catch(Exception e){} System.out.println(“Bye!”); }

(iii) import java.io.*; import java.util.*; public class Q1 { public static void main(String [] args) { try { Scanner keyboard = new Scanner(System.in); System.out.print("Enter 2 integers: "); int a = keyboard.nextInt(); int b = keyboard.nextInt(); int c = a/b; System.out.println("c: " + c); } catch(RuntimeException e){} System.out.println(“Bye!”); }

3

Question 2 – Checked and unchecked exceptions import java.io.*; public class Q2 { public static void main(String [] args) { FileWriter out = new FileWriter(new File("OutputData.txt")); out.write("I am writing to you ..."); out.close(); } }

The program does not compile successfully. The compiler gives an error message, part of which is shown below: WriteToFile.java:7: unreported exception java.io.IOException; must be caught or declared to be thrown

a)

Is IOException a checked exception or an unchecked exception? How can you tell?

b)

IOException is a subclass of Exception. True or false?

c)

IOException is a subclass of RuntimeException. True or false?

d)

Re-write the given program so that the program compiles, but the IOException will not be handled by the main method.

e)

Re-write the given program so that the IOException, if thrown, will be handled by the main method. Try to display the maximum amount of information about the exception.

4

Question 3 – Using API documentation to determine exceptions import java.util.*; public class Q3 { public static void main(String [] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter an integer: " String token = keyboard.next(); int n = Integer.parseInt(token); System.out.println("The integer entered is " } }

// line 1 // line 2 // line 3 // line 4 + n); // line 5

The above program compiles successfully. The API documentation gives the following method declarations: •

In class Scanner: public Scanner(InputStream source)



In class PrintStream: public void print(String s)



In class Scanner: public String next() throws NoSuchElementException, IllegalStateException



In class Integer: public static int parseInt(String s) throws NumberFormatException



In class PrintStream: public void println(String s)

a)

It is possible for the program to run without any exception being thrown. True or false?

b)

On which lines can an exception be thrown?

c)

Is NumberFormatException a checked or unchecked exception?

d)

Will an exception be thrown if the user enters as input i)

123

ii)

abc

iii) 12.3 iv)

+123

v)

-123

5

Question 4 – The try statement import java.io.*; import java.util.*; public class Q4 { public static void main(String [] args) { try { Scanner keyboard = new Scanner(System.in); System.out.print("Enter 2 integers: "); int a = keyboard.nextInt(); int b = keyboard.nextInt(); int c = a/b; System.out.println("c: " + c); } catch (ArithmeticException e) { System.out.println("An arithmetic error has occurred!"); } catch (RuntimeException e) { System.out.println("An error has occurred!"); } finally { System.out.println("Program ends"); } } }

The above program compiles successfully. a)

What is the output if the user enters the following in response to the prompt to enter two integers? i)

10 5

ii)

10 0

iii)

10 abc

iv) 10 2.5

b)

The order of the two catch blocks can be reversed and the program still compiles and runs. True or false?

c)

The two catch blocks can be removed and the program still successfully compiles. True or false?

6

Question 5 – The try statement import java.io.*; import java.util.*; public class Q5 { public static void main(String [] args) { try { String fileName = "infile.txt"; Scanner in = new Scanner(new File(fileName)); String input = in.next(); int value = Integer.parseInt(input); } catch (IOException e) { System.out.println(e); // line 5 } catch (NumberFormatException e) { System.out.println(e); // line 6 } } }

// // // //

line line line line

1 2 3 4



The above program compiles successfully.



The statement on line 2 will throw a FileNotFoundException if the file does not exist.

a)

If the file exists and contains two integers, which statements of the program will be executed?

b)

If the file exists but is empty, which statements of the program will be executed?

c)

If the file does not exist, which statements of the program will be executed?

d)

Re-write the program to specifically catch a FileNotFoundException.

7

Question 6 – Defining exception classes and throwing exceptions Task 1: Write a program in a file called ConvertToKm.java that converts a distance in miles to kilometres (where 1 mile = 1.61 km). The program should prompt the user, read in a distance (miles) from the keyboard, and display the converted distance (kilometres) to screen. The distance should be positive. Note that at this stage, the program is written without considering exceptions. A sample run is shown below: Please enter miles (double): 2.5 Converted to kilometers: 4.025

Task 2: For the program you have written, what do you think can go wrong? Use a table below to record your answer What can go wrong

Detected by

Handled by

What will be the response?

Task 3: Define the checked exception class NegativeNumberException. Task 4: Modify the previous program to throw an exception when the user enters a negative distance. Task 5: Modify the program to inform the user of the types of errors he or she has made in entering the distance. The program must also terminate gracefully in all cases.



8...


Similar Free PDFs