1
|
- By
Tony Gaddis
- Modified by
- Elizabeth Adams
|
2
|
- Today
- Exceptions
- Handling Exceptions
- Throwing Exceptions
- Thursday
- File handling
- Advanced Topics:
- Binary Files,
- Random Access Files, and
- Object Serialization
|
3
|
- An exception is an object that is generated as the result of an error or
an unexpected event.
- Unhandled exceptions cause programs to bomb.
- This is not a good thing, particularly if the program is flying a plane
or administering radiation, or running a nuclear reactor.
- Exceptions are runtime NOT compile time errors.
|
4
|
- In Java, exceptions are said to have been “thrown.” In other languages, they may be
“raised.”
- It is the programmers responsibility to write code that anticipates the
occurrence of an exception and keeps the program from crashing.
- The code that does this is said to “handle” the exception and is called
an exception handler.
- If the programmer doesn’t write
code to “handle the exception”, the
default exception handler does.
It prints an error message and crashes the program which isn’t
very satisfactory.
|
5
|
|
6
|
- To handle an exception, you use a try catch block try
- {
- (try block statements...)
- }
- catch (ExceptionType ParameterName)
- {
- (catch block statements...)
- }
- try block contains code that might cause an exception to occur
- catch indicates the exception that you expect to catch and how you want
to handle it.
|
7
|
- A catch clause begins with the key word catch and has a parameter list
consisting of the type of the exception and a variable name.
- catch (ExceptionType ParameterName)
- The code between the required curly braces following the catch clause
will be executed if the try block throws the referenced exception.
- The Java Virtual Machine searches for a catch clause that can deal with
the exception
|
8
|
- Each exception object has a method named getMessage that can be used to
retrieve the default error message for the exception.
- Example: ExceptionMessage.java is a file in your text on page 728
|
9
|
- The parameter must be of a type that is compatible with the thrown
exception’s type
- this means don’t have a catch (ArithmeticException ae) if the exception
you expect to occur is a (FileNotFoundException fnfe) because it won’t
catch it.
- After an exception is handled, the program will leave the catch block
and continue execution at the point following it.
|
10
|
- When handling exceptions, you can use a polymorphic reference (see page
730) as a parameter in the catch clause but do not do so in this course.
- This means that although you can catch any exception that is derived
from the Exception class with catch(Exception
e) you should not.
- The exceptions that you must handle are the checked exceptions . They are derived from the Exception class.
- There are unchecked exceptions derived from RuntimeException which can be
ignored but you should not ignore them in this course.
|
11
|
- The code in the try block may be capable of throwing more than one type
of exception.
- A separate catch clause needs to be written for each type of exception
that could potentially be thrown.
- The JVM will run the first compatible catch clause it finds.
|
12
|
- A try statement may have only one catch clause for each specific type of
exception.
- try
- {
- number = Integer.parseInt(str);
- }
- catch (NumberFormatException nfe)
- {
- System.out.println("Bad
number format.");
- }
- catch (NumberFormatException nfe) // is an ERROR because
NumberFormatException has already been caught
- {
- System.out.println(str + "
is not a number.");
- }
|
13
|
- The NumberFormatException class is derived from the
IllegalArgumentException class.
- this means that the IllegalArgumentException class is more general than
the NumberFormatException
- try
- {
- number = Integer.parseInt(str);
- }
- catch (IllegalArgumentException e)
- {
- System.out.println("Bad
number format.");
- }
- catch (NumberFormatException e) // this is an ERROR because the more
specific exception follows the more general exception.
- {
- System.out.println(str + "
is not a number.");
- }
|
14
|
- The try statement may have an optional finally clause.
- If present, the finally clause must appear after all of the catch clauses.
- try
- {
- (try block statements...)
- }
- catch (ExceptionType ParameterName)
- {
- (catch block statements...)
- }
- finally
- {
- (finally block statements...)
- }
|
15
|
- The finally block is one or more statements,
- that are always executed after the try block has executed and
- that are always executed after any catch blocks have executed if an
exception was thrown.
- The statements in the finally block execute whether an exception occurs
or not.
|
16
|
- 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.
- It indicates:
- the method that was executing when an exception occurred and
- all of the methods that were called in order to execute that method.
|
17
|
- When an exception is thrown, it cannot be ignored.
- It must be handled by the program, or by the default exception handler.
- When the code in a method throws an exception:
- normal execution of that method stops
- the JVM searches for a compatible exception handler inside the method.
|
18
|
- If there is no exception handler inside the method:
- control of the program is passed to the previous method in the call
stack.
- If that method has no exception handler, then control is passed again,
up the call stack, to the previous method.
- If control reaches the main method:
- the main method must either handle the exception, or
- the program is halted and the default exception handler handles the
exception.
|
19
|
- There are two categories of exceptions:
- Unchecked exceptions derived from
Error, which are thrown when a critical error occurs, should not be
handled.
- Unchecked exceptions derived from RuntimeException should be handled or
prevented.
- Checked exceptions derived from Exception have to be handled by you.
|
20
|
- If the code in a method can throw a checked exception, the method:
- must handle the exception, or
- it must have a throws clause listed in the method header.
- The throws clause informs the compiler what exceptions can be thrown
from a method and avoids a compile time error
|
21
|
- You can write code that:
- throws one of the standard Java exceptions, or
- an instance of 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.
|
22
|
- 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("Out of fuel");
- Note: Don’t confuse the throw statement with the throws clause.
- Text example: DateComponentExceptionDemo.java
|
23
|
- You can create your own exception classes by deriving them from the Exception
class or one of its derived classes.
- Text example:
- BankAccount.java
- NegativeStartingBalance.java
- AccountTest.java
|
24
|
- Some examples of exceptions that can affect a bank account: These should be handled by program not
as exceptions.
- A negative starting balance is passed to the constructor.
- A negative interest rate is passed to the constructor.
- A negative number is passed to the deposit method.
- A negative number is passed to the withdraw method.
- The amount passed to the withdraw method exceeds the account’s balance.
- We can create exceptions that represent each of these error conditions but
that would be stupid.
|
25
|
- General format
- @exception ExceptionName Description
- Remember:
|