starting out with java: early objects third edition by tony gaddis as modified for csci 1260
DESCRIPTION
Chapter 10: Exceptions and Advanced File I/O. Starting Out with Java: Early Objects Third Edition by Tony Gaddis as modified for CSCI 1260. Chapter Topics. Chapter 10 discusses the following main topics: Handling Exceptions Throwing Exceptions Getting Current Date and Time - PowerPoint PPT PresentationTRANSCRIPT
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Starting Out with Java: Early Objects Third Edition
by Tony Gaddis as modified for CSCI 1260
Chapter 10:Exceptions and Advanced File I/O
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-2
Chapter Topics
Chapter 10 discusses the following main topics: Handling Exceptions Throwing Exceptions Getting Current Date and Time More about Java Packages More about Input/Output Streams Advanced Topics:
• Binary Files, • Random Access Files, and • Object Serialization
Not covered in class
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Dealing with Error Situations• There are 3 major categories of errors with which we must deal:
Compile-time errors – mostly involving Java syntax errors (missing semicolon, misspelled name, missing import, etc.)
• Eclipse helps us out with these, giving squiggly lines, messages, tool-tips, and other information about the errors and, often, suggestions about what to do to correct them
Run-time errors – the program crashes as it is running• This chapter is mostly about dealing with this type of error.
Logic Error – the program compiles and runs, but some or all of the results are incorrect
• Often the hardest errors to discover and correct because one has to test the program thoroughly even to know that there are flaws
• Just because a program has no syntax errors and runs without crashing does not mean the results it produces are correct.
• Test, test, test, test, test, test!
10-3
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-4
Handling Exceptions
• An exception is an object that is generated as the result of an error or other unexpected event.
• Exceptions are said to “thrown.” • It is the programmer’s responsibility to write code that detects and handles
exceptions. Java allows you to create exception handlers – pieces of code that execute only if
an exception has occurred. Unhandled exceptions will crash a program.
• If an exception occurs and there is no handler to deal with the exception, the program crashes.
• It displays a message and the program is terminated.
• Example: BadArray.java – see next slide
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Runtime Error Example
10-5
Loop goes too far. Array has 3 items with subscripts 0,
1, and 2. This loop tries to
access item in subscript position 3 – then it crashes
The program worked correctly for subscripts 0, 1, and 2, but crashed for subscript 3
Line number where error was detected
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-6
Handling Exceptions• An exception handler is a section of Java code that gracefully responds to
exceptions. “Gracefully” means that the program deals with the exception in some rational way
without simply “crashing” the program• It might try to correct the problem and continue• It might display a message alerting the user to take a corrective action• It might save all the information, display a clear message, and terminate the program
“normally.”• And so forth …
• The process of intercepting and responding to exceptions is called exception handling.
• A default exception handler is provided by Java to deal with exceptions that occur but that the program does not handle. The default exception handler displays an error message and crashes the
program. See previous slide for an example of Java’s default exception handler at work.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-7
Exception Classes
• An exception is an object.• Exception objects are created from classes in the
Java API hierarchy of exception classes.• All of the exception classes in the hierarchy are
derived from the Throwable class.• Error and Exception are derived from the Throwable class.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-8
Exception Classes
• Classes that are derived from Error are for exceptions that are thrown when critical errors occur. Examples of these are An internal error in the Java Virtual Machine Running out of memory
• Applications should not try to handle these errors because they are the result of serious conditions that are beyond the ability of application programs to handle
• Programmers should handle the exceptions that are instances of classes that are derived from the Exception class
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-9
Exception ClassesObject
Throwable
ExceptionError
RuntimeExceptionIOException
FileNotFoundExceptionEOFException
…
…
…
…
More info available at http://java.sun.com/javase/6/docs/api/
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-10
Handling Exceptions• To handle an exception, you use a try statement.
try{ (try block statements go here ...)}catch (ExceptionType ParameterName){ (catch block statements go here ...)}
• The keyword try indicates a block of code will be attempted (the curly braces are required) and monitored for possible exceptions This block of code is known as a try block. Note that this is not necessarily an indication of a lack of confidence in the correctness of our code – there
are many reasons that correct code can encounter exceptional conditions such as• Bad input from user (garbage in, garbage out)
• Out of memory
• Disk, CD, or thumb drive is full, read-only, or offline
• Hardware failure or network problem
• Security issue blocking necessary access
• And many others …
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-11
Handling Exceptions
• A try block contains: One or more statements that are to be executed Some of the statements can potentially result in an exception being
thrown
• The application will not automatically halt if the try block throws an exception – because the application may intercept it and deal with it
• If code that is not in a try block throws an exception: The program cannot intercept it and handle it The system takes a standard action – usually crashes the program
• After the try block, a catch block appears
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-12
Handling Exceptions• A catch clause begins with the key word catch:
catch (ExceptionType ExceptionObjectName) ExceptionType is the name of an exception class and ExceptionObjectName is a variable name that will reference the
exception object if the code in the try block throws an exception This is similar to a method’s parameter, but
• There may be only one parameter • It must be of some Exception type
• The code that immediately follows the catch clause is known as a catch block (the curly braces are required)
• The code in the catch block is executed if and only if the try block throws an exception
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-13
Handling Exceptions - example• This code handles a FileNotFoundException if it is thrown - it simply
displays a message and then continues with the program.try{ File file = new File ("MyFile.txt"); Scanner inputFile = new Scanner(file);}catch (FileNotFoundException e){ System.out.println("File not found.");}
• The Java Virtual Machine searches for a catch clause that can deal with the exception.
• Example: OpenFile.java
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-14
Handling Exceptions
• The parameter for a catch block must be of a type that is compatible with the thrown exception’s type. Otherwise, the catch handler will not catch it when it is thrown
• After an exception is handled, the program will continue execution at the point just past the catch block Note that control does NOT return to point of the exception If, after handling the exception, you wish to retry the try block,
you must put it in a loop such as a while loop
• If no exception is thrown, execution skips the catch block completely and continues after the catch block.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Example
10-15
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-16
Handling Exceptions
• Each type of exception class has a message field that allows one to store a message in the exception object that is thrown For standard exception classes in Java, there is a default message The message gives some information about the reason the exception
was thrown
• Each exception object has a method named getMessage that can be used to retrieve the error message associated with that exception.
• Example: ExceptionMessage.java ParseIntError.java
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Example: ParseIntError
10-17
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-18
Polymorphic References To Exceptions
• Most exceptions thrown are objects of classes derived from the Exception class. Therefore, when handling exceptions, you can use a
polymorphic reference as a parameter in the catch clause (using the is-a relationship provided by the inheritance mechanism in Java)
A catch clause that uses a parameter variable of the Exception type can catch any thrown exception derived from the Exception class
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-19
Polymorphic References To Exceptionstry{ number = Integer.parseInt(str);}catch (Exception e){ System.out.println("The following error occurred: "
+ e.getMessage());}
• The Integer class’s parseInt method throws a NumberFormatException object if the argument cannot be converted to an integer (for example, if str = “Samantha”;) The NumberFormatException class is derived from the Exception class. Thus, this catch handler can catch it, making life easier
• One doesn’t have to know the specific type of exception that might be thrown• If a try block might throw one of several different exceptions, one catch handler might be able to
handle all of them
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-20
Handling Multiple Exceptions• The code in the try block may be capable of throwing
more than one type of exception.• A separate catch clause may to be written for each
type of exception that could potentially be thrown if different actions are required to handle each different type of exception
• The JVM will run only the first compatible catch clause found.
• The catch clauses must be listed from most specific to most general.
• Example: SalesReport.java, SalesReport2.java
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-21
Exception Handlers• There can be many polymorphic catch clauses.• A try statement may have only one catch clause for each specific
individual type of exception.try{ number = Integer.parseInt(str);}catch (NumberFormatException e){ System.out.println("Bad number format.");}catch (NumberFormatException e) // ERROR!!!{ System.out.println(str + " is not a number.");} Error to have a second handler for the same
type of exception – we could never reach it anyway since the first catch would have
handled the exception
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-22
Exception Handlers
• The NumberFormatException class is derived from the IllegalArgumentException class. The following is not valid because the first catch handler would catch everything the second handler
could catch. The more general handler is given before the more specific handler – WRONG!!!
try{ number = Integer.parseInt(str);}catch (IllegalArgumentException e){ System.out.println("Bad number format.");}catch (NumberFormatException e) // ERROR!!!{ System.out.println(str + " is not a number.");}
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-23
Exception Handlers• The previous code could be rewritten to work, as follows,
without errors, by placing the most specific type first and the more generic type after it.
try{ number = Integer.parseInt(str);}catch (NumberFormatException e) //More specific type{ System.out.println(str + " is not a number.");}catch (IllegalArgumentException e) //OK–parent class{ System.out.println("Bad number format.");}
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The finally Clause• Sometimes, one needs to take some specific
action(s) regardless of whether an exception was thrownExamples
• If a file has been opened, it should be closed before the program ends regardless of whether an exception was thrown in the meantime
• If data has been calculated, before ending the program, one may need to save it to a file or a database whether or not an exception has been thrown subsequently
• If one has connected to a network or a database or some other resource that is no longer needed, it may be necessary to disconnect regardless of whether an exception has been thrown
10-24
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-25
The finally Clause• For this purpose, a finally clause may be used with a try/catch.• The finally clause is optional. It is only used if it is needed to specify an
action that should be done whether an exception was thrown on not.• If present, the finally clause must appear after the last catch clause.
try{ (try block statements...)}catch (ExceptionType ParameterName){ (catch block statements...)}finally{ (finally block statements...)}
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-26
The finally Clause
• The finally block contains one or more statements These statements are always executed after the try
block has executed and After a catch block was executed if an exception
was thrown• The statements in the finally block execute
whether an exception occurs or not.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The Stack Trace• When a Java program is executing, the system tracks
the execution historyFor example, if method m1 invokes method m2, the system
has to remember where it was in m1 so that when m2 finishes and returns, the system knows where to return.
If a program crashes, the execution history not only tells you where you were in the program when it crashed but also how you got there• The latter is important because a method might be invoked from
many different places in a program and knowing which invocation caused the crash may help you find and correct the problem
• The execution history is called the stack trace
10-27
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-28
The Stack Trace• The call stack is an internal list of all the methods that are currently executing.• A stack trace is a list of all the methods in the call stack. • Reviewing the stack trace when an exception occurs allows one to determine
the method that was executing when the exception occurred and all of the methods that were called in order to get to that method
• A stack trace may be shown by Java’s default exception handler when an unhandled exception occurs
• From a catch block, one may display a stack trace without involving Java’s default exception handler. If e is the exception object, to display the stack trace, use
e.printStackTrace ( );• Example: StackTrace.java
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-29
Uncaught Exceptions• When an exception is thrown, it cannot be
ignored.• It must be handled by the program, or it will be
handled by the default exception handler.• When the code in a method throws an exception:
normal execution of that method stops, and the JVM searches for a compatible exception handler
inside the method. Continued on next slide …
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-30
Uncaught Exceptions• If there is no matching exception handler inside the
method: control of the program is passed back to the previous method
in the call stack – that is, to the invoking method If that method has no matching exception handler, then
control is passed again, up the call stack, to the previous method – the method that invoked it
• If control reaches the main method: the main method must either handle the exception, or the program is halted and the default exception handler for
Java handles the exception
main m1 m2 m3 m4
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Throwing your own exceptions• If you detect an exceptional condition, you
may throw your own exceptionIt may be an exception object of one of the Java
exception typesIt may also be an exception object of a type that
you create• For example
if (num > 0) average = total / num;
else throw new Exception(“Cannot divide by 0”);
10-37
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-38
Throwing Exceptions
• You can write code that throws an instance of: one of the standard Java exceptions a custom exception class that you have designed
• The throw statement is used to manually throw an exception. throw new ExceptionType(MessageString);
• The throw statement causes an exception object to be created and thrown.
• The MessageString parameter is the value assigned to the message field of the exception object.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-39
Throwing Exceptions• The MessageString argument contains a custom error
message that can be retrieved from the exception object’s getMessage method.
• If you do not pass a message to the constructor, the exception will have a null message.throw new Exception(“Dose too high – patient dead"); Note: Don’t confuse the throw statement with the throws
clause.• Examples:
InventoryItem.java, InventoryDemo.java
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-40
Creating Exception Classes• You can create your own exception classes by deriving them from the Exception class or one of its derived classes.
• Example: BankAccount.java, NegativeStartingBalance.java, AccountTest.java
Derived from Exception
Base-class constructor sets message
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The Current Date and Time• To get and format the current date for display
use code similar to the following
10-43
Must import these two classes
Output produced
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Current Date and Time• Dealing with the current time is similar
10-44
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Creating your own named Java packages• A package is a collection of related classes• You may create your own and not always use
the “default package” in Eclipse
10-45
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Your own packages• Once the package is created, you may add
classes to it in the same way you would for the default package in previous exercises
• To use this package in another project or in another package in the same project, you must import it:import myUtilityClasses;
10-46