Lab 10 Basic Exception Handling

advertisement
Lab 10
CS2312 Problem Solving and Programming (2015/2016 Semester B) | www.cs.cityu.edu.hk/~helena
Lab 10 Basic Exception Handling
Section I - [ Hints for Assignment Phase 1]
Section II - MC on Exception Handling
Section I - Programming Exercise for Exception Handling
Task 0: Read the following useful note:
Great tricks / hotkeys in Eclipse 1. Ctrl‐M: maximize / restore current view 2. Ctrl‐F6: goto the previous view 3. F3: quickly goto the declaration of the method/class/field  4. Alt‐Shift‐R: Refractor/Rename a file name, or a method/class/field name, etc.. and update all references 5. Add throws declaration 6. Surround with Try‐catch block Task 1: Extend Lab08-Q2 (AddSalary) to handle abnormal cases by exception handling.
[Your task] Follow and learn the given steps in the following pages 
-1-
Lab 10
CS2312 Problem Solving and Programming (2015/2016 Semester B) | www.cs.cityu.edu.hk/~helena
Step 1. Download the given files for testing. Study the following testcases and expected outputs:
e2a.txt
3
Helena 10000 7
Jason 20000 21
Kit 30000 21
e2b.txt
3
Helena 10000 7
Jason 20000 21
e2c.txt
3
Helena 10000 7
Jason 20000 21
Kit 30000 21
e2d.txt
3
Helena 10000 7
Jason 20000 21
Kit 30000 21
e2e.txt
3
Helena 10000 7
Jason 20000 21
Kit 30000 21
e2f.txt
3
Helena 10000 7
Jason 20000 21
Kit 30000 21
addSalary Helena 5000
addSalary Helena 5000 addSalary Jason 2000 addSalary Grace 2000 deductSalary Jason 2000 addSalary Jason one hundred addSalary Jason
addSalary Jason 2000
addSalary Jason 2000
list
list
list
list
list
list
Missing one
staff record
OK
Please input the file pathname: e2b.txt File content problem. Program terminated. Please input the file pathname: e2a.txt > addSalary Helena 5000 Done. > addSalary Jason 2000 Done. > list Helena ($15000, 7 days) Jason ($22000, 21 days) Kit ($30000, 21 days) Please input the file pathname: e2d.txt > deductSalary Jason 2000 Unknown command - ignored!
Please input the file pathname: e2c.txt > addSalary Grace 2000 Employee not found!
> addSalary Jason 2000 Done. > list ..
Please input the file pathname: e2f.txt > addSalary Jason
Insufficient command
arguments!
> list ..
Please input the file pathname: e2e.txt > addSalary Jason one hundred Wrong number format!
> list ..
Please input the file pathname: e2g.txt File not found!
Step 2. Copy your Lab08-Q2 project. It should contain the following files:
Main.java, Company.java, Employee.java Command.java, RecordedCommand.java, AddSalary.java, ListAllRecords.java Add the following exception classes: ExEmployeeNotFound,ExInsufficientArguments,ExWrongCommand 2.1
ExEmployeeNotFound.java ======================== public class ExEmployeeNotFound extends Exception { public ExEmployeeNotFound() { super("Employee not found!"); } public ExEmployeeNotFound(String message) { super(message); } } Note: There is a warning about missing serialVersionUID.
Reason of the warning: The base class, Exception, implements the Serializable interface which
allows object data to be converted to/from byte streams. Exceptions are serializable so that
exceptions are capable of being sent across the wire in a distributed application.
Serializables (and thus Exceptions) require such an ID for controlling the versions of object data.
To remove the warning: choose one of the compiler's suggestions.
-2-
Lab 10
2.2
CS2312 Problem Solving and Programming (2015/2016 Semester B) | www.cs.cityu.edu.hk/~helena
Copy and paste ExEmployeeNotFound.java as ExInsufficientArguments.java Click to choose
Ctrl-C, then Ctrl-V
Type " ExInsufficientArguments.java"

ExInsufficientArguments.java
============================ Then, you only need to change this part
public class ExInsufficientArguments extends Exception { public ExInsufficientArguments() { super("Insufficient command arguments!"); } public ExInsufficientArguments(String message) { super(message); } } 2.3 Copy and paste ExEmployeeNotFound.java as ExWrongCommand.java Click to choose
Ctrl-C, then Ctrl-V
Type "ExWrongCommand.java"

ExWrongCommand.java ============================ You only need to change this part
public class ExWrongCommand extends Exception { public ExWrongCommand() { super("Wrong Command"); } public ExWrongCommand(String message) { super(message); } } Step 3. Edit Main.java as follows:
3.1 Add a throw statement for wrong command:
public static void main(String [] args) ... { Edit the code as:
... if (cmdParts[0].equals("addSalary"))
while (inFile.hasNext()) (new AddSalary()).execute(cmdParts); { String cmdLine = inFile.nextLine(); else if (cmdParts[0].equals("list")) if (cmdLine.equals("")) continue; (new ListAllRecords()).execute(cmdParts); System.out.println("\n> "+cmdLine); else if (cmdParts[0].equals("undo")) RecordedCommand.undoOneCommand(); String[] cmdParts = cmdLine.split(" "); if (cmdParts[0].equals("addSalary")) else if (cmdParts[0].equals("redo")) (new AddSalary()).execute(cmdParts); RecordedCommand.redoOneCommand(); if (cmdParts[0].equals("list")) else (new ListAllRecords()).execute(cmdParts); throw new ExWrongCommand(); if (cmdParts[0].equals("undo")) RecordedCommand.undoOneCommand(); if (cmdParts[0].equals("redo")) RecordedCommand.redoOneCommand(); } inFile.close(); in.close(); } -3-
Lab 10
CS2312 Problem Solving and Programming (2015/2016 Semester B) | www.cs.cityu.edu.hk/~helena
3.2 Prepare to handle the file not found exception
public static void main(String [] args) throws FileNotFoundException { .. Scanner inFile = null; String filepathname = in.nextLine(); inFile = new Scanner(new File(filepathname)); Scanner inFile = new Scanner(new File(filepathname)); 3,3 Highlight the following part  right-click and choose Suround with  Try/catch Block
3.4 Modify the try‐catch block as follows:
try { inFile = new Scanner(new File(filepathname)); int tot=inFile.nextInt(); Company company = Company.getInstance(); for (int i=0;i<tot;i++) company.add(new Employee(inFile.next(),inFile.nextInt(),inFile.nextInt())); while (inFile.hasNext()) { String cmdLine = inFile.nextLine(); if (cmdLine.equals("")) continue; System.out.println("\n> "+cmdLine); String[] cmdParts = cmdLine.split(" "); if (cmdParts[0].equals("addSalary")) (new AddSalary()).execute(cmdParts); .. else } catch (FileNotFoundException e)
{
throw new ExWrongCommand(); System.out.println("File not found!"); } } catch (InputMismatchException e) { } catch (FileNotFoundException e) { System.out.println("File content problem. Program terminated."); // TODO Auto‐generated catch block e.printStackTrace(); } catch (ExWrongCommand e) { System.out.println("Unknown command ‐ ignored!"); } catch (ExWrongCommand e) { } // TODO Auto‐generated catch block e.printStackTrace(); finally { } inFile.close(); if (inFile!=null) //If it has been opened successfully, close it inFile.close(); in.close(); in.close(); } -4-
Lab 10
CS2312 Problem Solving and Programming (2015/2016 Semester B) | www.cs.cityu.edu.hk/~helena
Step 4. Edit the findEmployee method (in Company.java):
public Employee findEmployee(String name)
{ for (Employee e: instance.allEmployees) if (e.getName().equals(name)) return e; First, edit the code as:
return null; } throw new ExEmployeeNotFound();  Then point to the red line and
choose "Add throws declaration"
Result:
public Employee findEmployee(String name) throws ExEmployeeNotFound { for (Employee e: instance.allEmployees) if (e.getName().equals(name)) return e; throw new ExEmployeeNotFound(); } Step 5. Edit AddSalary.java:
5.1 Highlight the following part  right-click and choose Suround with  Try/catch Block
5.2 Modify the try‐catch block as follows:
public void execute(String[] cmdParts)
{ try { Company company = Company.getInstance(); e = company.findEmployee(cmdParts[1]); addAmount=Integer.parseInt(cmdParts[2]); e.addSalary(addAmount); addUndoCommand(this); clearRedoList(); } catch (NumberFormatException e) {
System.out.println("Done."); System.out.println("Wrong number format!"); } catch (NumberFormatException e) { } catch (ExEmployeeNotFound e) { // TODO Auto‐generated catch block System.out.println(e.getMessage()); e.printStackTrace(); } } catch (ExEmployeeNotFound e) { // TODO Auto‐generated catch block e.printStackTrace(); } } -5-
Lab 10
CS2312 Problem Solving and Programming (2015/2016 Semester B) | www.cs.cityu.edu.hk/~helena
5.3 Add detection and handling of "insufficient arguments" as follows:
if (cmdParts.length<3) try { throw new ExInsufficientArguments(); Company company = Company.getInstance(); e = company.findEmployee(cmdParts[1]); addAmount=Integer.parseInt(cmdParts[2]); e.addSalary(addAmount); addUndoCommand(this); clearRedoList(); System.out.println("Done."); } catch (NumberFormatException e) { catch (ExInsufficientArguments e) { System.out.println("Wrong number format!"); System.out.println(e.getMessage()); } catch (ExEmployeeNotFound e) { System.out.println(e.getMessage()); } Test the program and submit your work to PASS. Finally, apply what you learn in this lab for your assignment. Section II - MC on Exception Handling
Submit your answers to the following questions to Canvas.
[Questions borrowed/revised from http://www.cs.armstrong.edu/liang/ ]
Part A - 9 Questions
[Part A] 1. A Java exception is an instance of __________. [Topic_06, P.5]
A. RuntimeException
B. Exception
C. Error
D. Throwable
E. NumberFormatException
[Part A] 2. An instance of _________ describes system errors. If this type of error occurs, there is
little you can do beyond notifying the user and trying to terminate the program gracefully.
[Topic_06, P.6]
A. RuntimeException
B. Exception
C. Error
D. Throwable
E. NumberFormatException
[Part A] 3. An instance of _________ describes programming errors, such as bad casting,
accessing an out-of-bounds array, and numeric errors.. [Guess and match Topic_06, P.5]
A. RuntimeException
B. Exception
C. Error
D. Throwable
E. NumberFormatException
-6-
Lab 10
CS2312 Problem Solving and Programming (2015/2016 Semester B) | www.cs.cityu.edu.hk/~helena
[Part A] 4. An instance of _________ are unchecked exceptions. [Topic_06, P.11]
A. RuntimeException
B. Exception
C. Error
D. Throwable
E. NumberFormatException
[Part A] 5. What exception type does the following program throw?
public class Test { public static void main(String[] args) { System.out.println(1 / 0); } } A. ArithmeticException
B. ArrayIndexOutOfBoundsException
C. StringIndexOutOfBoundsException
D. ClassCastException
E. No exception
[Part A] 6. What exception type does the following program throw?
public class Test { public static void main(String[] args) { int[] list = new int[5]; System.out.println(list[5]); } } A. ArithmeticException
B. ArrayIndexOutOfBoundsException
C. StringIndexOutOfBoundsException
D. ClassCastException
E. No exception
[Part A] 7. What exception type does the following program throw? [Ref Topic04 P.8]
public class Test { public static void main(String[] args) { Object o = new Object(); String d = (String)o; } } A. ArithmeticException
B. ArrayIndexOutOfBoundsException
C. StringIndexOutOfBoundsException
D. ClassCastException
E. No exception
[Part A] 8. What exception type does the following program throw?
public class Test { public static void main(String[] args) { Object o = null; System.out.println(o.toString()); } } A. ArithmeticException
B. ArrayIndexOutOfBoundsException
C. StringIndexOutOfBoundsException
D. ClassCastException
E. NullPointerException
-7-
Lab 10
CS2312 Problem Solving and Programming (2015/2016 Semester B) | www.cs.cityu.edu.hk/~helena
[Part A] 9. What exception type does the following program throw? [Worth to try in Eclipse!]
public class Test { public static void main(String[] args) { Object o = null; System.out.println(o); } } A. ArithmeticException
B. ArrayIndexOutOfBoundsException
C. StringIndexOutOfBoundsException
D. No exception
E. NullPointerException
Part B - 7 Questions
[Part B] 1. A method must declare to throw unhandled ________. [Topic_06, P.11]
A. Unchecked exceptions
B. Checked exceptions
C. Error
D. RuntimeException
[Part B] 2. Which of the following statements are true?
A. You use the keyword throws to declare exceptions in the method heading.
B. A method may declare to throw multiple exceptions.
C. To throw an exception, use the key word throw.
D. If a checked exception occurs in a method, it must be either caught or declared to be thrown
from the method.
[Part B] 3. What is wrong with the following code:
class Test { public static void main(String[] args) throws MyException { System.out.println("Welcome to Java"); } } class MyException extends Error { } A. You should not declare a class that extends Error, because an Error should raise a fatal error
that terminates the program.
B. You cannot declare an exception in the main method.
C. You declared an exception in the main method, but you did not throw it.
D. The program has a compilation error.
-8-
Lab 10
CS2312 Problem Solving and Programming (2015/2016 Semester B) | www.cs.cityu.edu.hk/~helena
[Part B] 4. Analyze the following code [Topic 06, P.9]
class Test { public static void main(String[] args) { try { String s = "5.6"; int k = Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; } catch (Exception ex) { System.out.println("NumberFormatException"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } } } A. The program displays NumberFormatException.
B. The program displays RuntimeException.
C. The program displays NumberFormatException followed by RuntimeException.
D. The program has a compilation error: catch (RuntimeException ex) should be specified before
catch (Exception ex).
[Part B] 5. Analyze the following program.
class Test { public static void main(String[] args) { try { String s = "5.6"; int k = Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } catch (Exception ex) { System.out.println(ex); } } } A. An exception is raised due to Integer.parseInt(s);
B. An exception is raised due to 2 / i;
C. The program has a compilation error.
D. The program compiles and runs without exceptions.
-9-
Lab 10
CS2312 Problem Solving and Programming (2015/2016 Semester B) | www.cs.cityu.edu.hk/~helena
[Part B] 6. What is displayed on the console when running the following program?
class Test { public static void main(String[] args) { try { method(); System.out.println("After the method call"); } catch (NumberFormatException ex) { System.out.println("NumberFormatException"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } } static void method() { String s = "5.6"; int k = Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } } A. The program displays NumberFormatException.
B. The program displays NumberFormatException followed by After the method call.
C. The program displays NumberFormatException followed by RuntimeException.
D. The program has a compilation error.
E. The program displays RuntimeException.
[Part B] 7. What is displayed on the console when running the following program?
class Test { public static void main(String[] args) { try { method(); System.out.println("After the method call"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } catch (Exception ex) { System.out.println("Exception"); } } static void method() throws Exception { try { String s = "5.6"; int k = Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } catch (Exception ex) { System.out.println("Exception"); } } } A. The program displays RuntimeException twice.
B. The program displays Exception twice.
C. The program displays RuntimeException followed by After the method call.
D. The program displays Exception followed by RuntimeException.
E. The program has a compilation error.
- 10 -
Lab 10
CS2312 Problem Solving and Programming (2015/2016 Semester B) | www.cs.cityu.edu.hk/~helena
Part C - 6 Questions
[Part C] 1. What is wrong in the following program? (Hint: A and D are not the answer)
class Test { public static void main (String[] args) { try { System.out.println("Welcome to Java"); } } } A. You cannot have a try block without a catch block.
B. You cannot have a try block without a catch block or a finally block.
C. A method call that does not declare exceptions cannot be placed inside a try block.
D. Nothing is wrong.
[Part C] 2. What is displayed on the console when running the following program?
class Test { public static void main (String[] args) { try { System.out.println("Welcome to Java"); return; } finally { System.out.println("The finally clause is executed"); } } } A. Welcome to Java
B. Welcome to Java followed by The finally clause is executed in the next line (The return
statement exits the method, but before exiting the method, the finally clause is executed.)
C. The finally clause is executed
D. None of the above
[Part C] 3. What is displayed on the console when running the following program?
class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2/i; System.out.println("Welcome to Java"); } catch (RuntimeException ex) { System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); } System.out.println("End of the block"); } } A. The program displays Welcome to Java three times followed by End of the block.
B. The program displays Welcome to Java two times followed by End of the block.
C. The program displays Welcome to Java two times followed by End of the block two times.
D. You cannot catch RuntimeException errors.
- 11 -
Lab 10
CS2312 Problem Solving and Programming (2015/2016 Semester B) | www.cs.cityu.edu.hk/~helena
[Part C] 4. What is displayed on the console when running the following program?
class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2/i; System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); } System.out.println("Very ending of the block"); } } A. The program displays Welcome to Java three times followed by End of the block.
B. The program displays Welcome to Java two times followed by End of the block.
C. The program displays Welcome to Java two times followed by End of the block two times.
D. The program displays Welcome to Java and End of the block, and then terminates because of
an unhandled exception.
[Part C] 5.
[Rethrowing Exceptions] What is displayed on the console when running the following program?
class Test { public static void main(String[] args) { try { method(); System.out.println("After the method call"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } catch (Exception ex) { System.out.println("Exception"); } } static void method() throws Exception { try { String s = "5.6"; int k = Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } catch (NumberFormatException ex) { System.out.println("NumberFormatException"); throw ex; } catch (RuntimeException ex) { System.out.println("RuntimeException"); } } } A. The program displays NumberFormatException twice.
B. The program displays NumberFormatException followed by After the method call.
C. The program displays NumberFormatException followed by RuntimeException.
D. The program has a compilation error.
[Part C] 6. Which of the following is not an advantage of Java exception handling?
A. Java separates exception handling from normal processing tasks.
B. Exception handling improves performance.
C. Exception handling makes it possible for the caller's caller to handle the exception.
D. Exception handling simplifies programming because the error-reporting and error-handling
code can be placed at the catch block.
- 12 -
Download