W3.java - Exceptions.ch14 and
W3.java - Exceptions.ch14 and
Primary Sources:
Chapter 11 in Supplementary Book (Murachs Java Programming)
Appendices C (pp. C6 C7) & E (pp. E1 E19) in Textbook (Carrano)
Secondary Sources:
[1] Ch. 9: Error Handling with Exceptions, Thinking in Java, B. Eckel, 2002
http://www.smart2help.com/e-books/tij-3rd-edition/TIJ311.htm
[2] A. Miller, G. Simmons, Exception Handling: Common Problems and Best Practice with Java 1.4,
In Net.ObjectDays , 2002. (http://www.old.netobjectdays.org/pdf/02/papers/industry/1430.pdf).
[3] R. Waldhoffs Weblog, Java's checked exceptions were a mistake, 2003,
http://radio-weblogs.com/0122027/stories/2003/04/01/JavasCheckedExceptionsWereAMistake.html
[4] B. Eckels Midview, Does Java need Checked Exceptions?, 2007.
http://www.mindview.net/Etc/Discussions/CheckedExceptions
Slide 1
Motivation
Watch the Apple Keynotes Network Meltdown, 2010,
http://gizmodo.com/5557458/watch-the-apple-keynotes-network-meltdown
WWDC keynotes are usually carefully orchestrated affairs. But you might have just
read in our live blog how Steve Jobs had to bail on a demo because of network
trouble. Awkward.
Apple attempted to do their demo over Wi-Fi, but as you can see couldn't manage to
get things up and running due to overload. So Jobs had to ask everyone in the
audience, repeatedly, to shut off their Wi-Fi so the show could go on. A bizarre
hiccup for a company in its prime, showing off its latest wares.
Slide 2
Java Exceptions: Simple Example
import java.util.Scanner;
public class DemoSimpleExceptions {
public static int quotient( int numerator, int denominator)
{ return numerator / denominator; }
public static void main( Strings[] args ) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an integer numerator: ");
int x = sc.nextInt();
System.out.print("Enter an integer denominator: ");
int y = sc.nextInt();
int result = quotient( x, y );
System.out.println(quotient = , result );
}
}
A. What happens if the user enters 10 for numerator and 3 for denominator when prompted?
quotient = 3
B. What happens if the user enters 10 for numerator and 0 for denominator when prompted?
java.lang.ArithmeticException
C. What happens if the user enters 10 for numerator and abcd for denominator when prompted?
java.util.InputMismatchException
Slide 3
Motivation
User Perspective: Robust Software
How do you feel when a software freezes, crashes, or gives blue screen of death?
Example: glitch in Apple iphone4 demo by Steve Jobs (2010)
Slide 4
Java Exceptions: Simple Example Revisited
import java.util.Scanner;
public class DemoSimpleExceptions {
public static int quotient( int numerator, int denominator)
{ return numerator / denominator; }
public static void main( Strings[] args ) {
Scanner sc = new Scanner(System.in);
boolean problem = true;
do {
try {
System.out.print("Enter an integer numerator: ");
int x = sc.nextInt();
System.out.print("Enter an integer denominator: ");
int y = sc.nextInt(); int result = quotient( x, y );
System.out.println(quotient = , result );
problem = false;
} catch (ArithmeticException e) {
System.out.println(An ArithmeticException ! );
} catch (InputMismatchException e) {
System.out.println(InputMisMatchException ! );
}
} while ( problem );
}
}
Slide 5
Outline
Objectives
Basic Concepts
Handling and Exception
Throwing an Exception
Programmer Defined Exception Classes
Review Quiz
Slide 6
Objectives
Applied
Given a method that throws one or more exceptions, code a
method that calls that method and catches the exceptions.
Given a method that throws one or more exceptions, code a
method that calls that method and throws the exceptions.
Code a method that throws an exception.
Use the methods of the Throwable class to get information
about an exception.
Code a class that defines a new exception, and then use that
exception in an application.
Use an assert statement in an application to make an assertion
about a condition.
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 7
Objectives (cont.)
Given Java code that uses any of the language elements
presented in this chapter, explain what each statement does.
Knowledge
Explain what assertions are and how you can use them in
your applications.
Describe the Throwable hierarchy and the classes that are
derived from it.
Describe the difference between checked and unchecked
exceptions and explain when you need to catch each.
Explain how Java propagates exceptions and how it uses the
stack trace to determine what exception handler to use when
an exception occurs.
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 8
Objectives (cont.)
Describe the order in which you code the catch clauses in a
try statement.
Explain when the code in the finally clause of a try statement
is executed and what that code typically does.
Explain what it means to swallow an exception.
Explain how a try-with-resources statement works.
Explain how a multi-catch block works.
Describe three situations where you might want to throw an
exception from a method.
Describe two situations where you might create a custom
exception class.
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 9
Outline
Objectives
Basic Concepts
Java Throwable Hierarchy
Error
Exceptions: Checked & Unchecked
Handling and Exception
Throwing an Exception
Programmer Defined Exception Classes
Review Quiz
Slide 10
The Throwable hierarchy
Throwable
Error Exception
Unchecked
RuntimeException
errors
Unchecked Checked
exceptions exceptions
assert statement
assert booleanExpression [: message ];
Note: Assert statement is used for debugging. It prints a message and exits a program.
By default assert statement are disabled at runtime
Ex. java ea myProgram executes myProgram with assertions enabled.
Q? How does one switch it on in Eclipse for debugging?
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 12
What are Java (Errors &) Exceptions?
Errors: catastrophic events justifying termination of program
Exception: non-catastrophic unusual events
Q? Have we come across any Exceptions so far? Name a few.
Throwable
Errors
AssertionError,
LinkageError , e.g., NoClassDefFoundError
VirtualMachineError e.g., OutOfMemoryError
Exception:
ClassNotFound
IOException
EOFException, FileNotFoundException
run-timeException
ArithmeticException
IllegalArgumentException
IndexOutOfBoundException , e.g., ArrayIndexOutOfBoundsException
NullPointerException
Slide 14
Common checked exceptions
ClassNotFoundException
IOException
EOFException
FileNotFoundException
NoSuchMethodException
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 15
Outline
Objectives
Basic Concepts
Handling an Exception
throw, catch
try {} catch {} finally {} statement
Multi-exception catch
Methods on exceptions: getMessage(), toString(), printStackTrace()
Throwing an Exception
Programmer Defined Exception Classes
Review Quiz
Slide 16
Handling checked exceptions
Throw the exception to the calling method MethodA()
{
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 17
The syntax of the try statement
try {statements}
[catch (MostSpecificExceptionType e) {statements}]
...
[catch (LeastSpecificExceptionType e) {statements}]
[finally {statements}]
Simple Example:
class TryCatch {
public static void main(String args[ ])
{ try {
if (args.length > 0) throw(new Exception("Thrown"));
return;
}
catch(Exception e)
{ System.out.println("Exception caught");return;}
finally
{ // Execute this Code block, no matter how try block exited!
System.out.println("finally");
}
}
} Console output: Alternative Console output:
Exception caught finally
finally
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 18
The syntax of the try statement
try {statements}
[catch (MostSpecificExceptionType e) {statements}]
...
[catch (LeastSpecificExceptionType e) {statements}]
[finally {statements}]
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 19
Review Quiz: Exception Handling
1. From which problems is it possible for a program to recover?
(a) Errors, e.g., divide by zero, deference a null pointer, ...
(b) Exceptions, e.g., ArithmeticException, NullPointerException, ...
(c) Both errors and exceptions
2. Which exceptions is a program required to catch?
(a) None. You can write a program to catch just the exceptions you want.
(b) All. If a program is not written to catch all exceptions it will not compile.
(c) Checked Ones, e.g., a program can not do I/O unless it catches all exceptions.
3. Which statement is FALSE about the try{} block?
(a) Some of the statements in a try{} block will never throw an exception.
(b) The statements in a try{} block may throw several types of exception.
(c) The try{} block can not contain loops or branches.
(d) The try{} block must appear before the catch{} blocks.
4. Which statement is FALSE about catch{} blocks?
(a) There can be several catch{} blocks in a try/catch structure.
(b) The catch{} block for a child exception class must PRECEED that of a parent execption class.
(c) The catch{} block for a child exception class must FOLLOW that of a parent execption class.
(d) If there is no catch{} block there must be a finally{} block.
5. When is a finally{} block executed?
(a) Only when an unhandled exception is thrown in a try{} block.
(b) Only when any exception is thrown in a try{} block.
(c) Always after execution has left a try{} block, no matter for what reason.
(d) Always just as a method is about to finish.
Slide 20
The syntax of the try statement
try {statements}
[catch (MostSpecificExceptionType e) {statements}]
...
[catch (LeastSpecificExceptionType e) {statements}]
[finally {statements}]
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 21
The syntax of the try-with-resources statement
try (statement[;statement] ...) {statements}
[catch (MostSpecificExceptionType e) {statements}] ...
[catch (LeastSpecificExceptionType e) {statements}]
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 22
Four methods available from all exceptions
getMessage()
toString()
printStackTrace()
printStackTrace(outputStream)
Leading Question:
Should error message be printed on standard output?
Is there an alternative ?
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 23
How to print exception data to the error output stream
catch(IOException e)
{
System.err.println(e.getMessage() + "\n");
System.err.println(e.toString() + "\n");
e.printStackTrace();
return null;
}
java.io.FileNotFoundException: c:\murach\java\files\produx.txt
(The system cannot find the file specified)
java.io.FileNotFoundException: c:\murach\java\files\produx.txt
(The system cannot find the file specified)
at java.io.RandomAccessFile.open(Native Method)
at java.io.RandomAccessFile.<init>(RandomAccessFile.java:233)
at java.io.RandomAccessFile.<init>(RandomAccessFile.java:118)
at ProductApp.readFirstLine(ProductApp.java:70)
at ProductApp.main(ProductApp.java:10)
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 24
Syntax of multi-exception catch block
catch (ExceptionType
| ExceptionType
[| ExceptionType]... e)
{statements}
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 25
A method with a single-exception catch block
public static String readFirstLine(String path)
{
try (RandomAccessFile in = new RandomAccessFile(path, "r"))
{ String line = in.readLine(); // may throw IOException
return line;
}
catch (FileNotFoundException e)
{ System.err.println(e.toString()); return null; }
catch (EOFException e)
{ System.err.println(e.toString()); return null; }
catch(IOException e) { e.printStackTrace(); return null; }
}
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 26
Outline
Objectives
Basic Concepts
Handling and Exception
Throwing Exception
Method header and checked Exception
Statement for Explicit Throw
Programmer Defined Exception Classes
Review Quiz
Slide 27
Declaration: Method may throw a checked exceptions
modifiers returnType methodName([parameterList])
throws exceptionList {}
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 28
Either Caller of getFileLength() catches IOException
public static int getRecordCount2(){
try
{ long length = getFileLength(); // may throw IOException
int recordCount = (int) (length / RECORD_SIZE);
return recordCount;
} catch (IOException e) {
System.err.println("An IO error occurred."); return 0;
}
}
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 29
Review Quiz: Exception Handling
1. Which of the following are checked exceptions?
(a.) OutOfMemoryError (b.) AssertionError (c.) ClassNotFoundException (d.) EOFException
(e.) FileNotFoundException (f.) NoSuchMethodException (g.) ArithmeticException
(h.) IllegalArgumentException (i.) IndexOutOfBoundsException (j.) NullPointerException
Slide 31
The syntax of the throw statement
throw throwableObject;
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 32
A method that throws an unchecked exception
public double calculateFutureValue(double monthlyPayment,
double monthlyInterestRate, int months)
{
if (monthlyPayment <= 0)
throw new IllegalArgumentException("Monthly payment must be > 0");
if (monthlyInterestRate <= 0)
throw new IllegalArgumentException("Interest rate must be > 0");
if (months <= 0)
throw new IllegalArgumentException("Months must be > 0");
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 33
Using throw statement in try (to test throw statement)
try
{ // code that reads the first line of a file
if (true) throw new IOException("I/O exception test");
return firstLine;
}
catch (IOException e)
{
// code to handle IOException goes here
}
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 34
Outline
Objectives
Basic Concepts
Handling and Exception
Throwing Exception
Programmer Defined Exception Classes
Review Quiz
Slide 35
When to define your own exceptions
When a method requires an exception that isnt provided by
any of Javas exception types
When using a built-in Java exception would inappropriately
expose details of a methods operation
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 36
Catching a programmer defined Exception
try
{
Product p = getProduct("1234");
}
catch (DAOException e)
{
System.out.println(e.getMessage());
}
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 37
Methods in Throwable class
getCause() // Get information on cause of an exception
initCause(cause) // Get initial trigger for a given cause
Resulting output
DAOException: Error reading the product
java.io.IOException: I/O exception test
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 38
Constructors of the Throwable class
Throwable(cause)
Throwable(message, cause)
Murach's Java Programming, C14 2011, Mike Murach & Associates, Inc. Slide 39
Outline
Objectives
Basic Concepts
Handling and Exception
Throwing an Exception
Programmer Defined Exception Classes
Review Quiz
Slide 40
Review Quiz: Exception Handling
1. When coding catch blocks, for exceptions you should always code them in what order?
(a.) More specific before less specific (b.) More general before specific, (c.) order does not matter
2. In which situation(s) would you typically not throw an exception from a method?
a. When you want to test an exception handler
b. When you need to perform some processing before exception is handled by calling method
c. When invalid arguments are passed to the method
d. When the exception is handled by the method
3. Which of the following statements is not true about assertions?
a. They let you test a condition as an application executes.
b. They let you print information to the standard error stream when an AssertionError occurs.
c. They let you change the values of variables as an application executes.
d. They can be enabled or disabled as an application executes.
4. In which of the following situations should you define a custom exception class?
a. When you want to change the message for an exception
b. When none of the Java exceptions are appropriate
c. When using a Java exception would expose too many details of a methods operation.
d. All of the above.
5. The try-with-resources statement doesnt need a finally clause because it
a. uses a multi-catch block to catch all exceptions
b. implements the AutoCloseable interface
c. automatically closes all declared resources
d. catches all exception that are thrown when you try to close a resource Slide 41
Review Quiz: Exception Handling
1. What is wrong with the following exception handler as written?
try { }
catch (Exception e) { }
catch (ArithmeticException a) { }