Title: Exceptions
1Exceptions
2- Even if you design your program with the utmost
care, insuring that every method works correctly
when interacting with other objects is a tedious
process. - The is especially true when others use the
classes you design. - Things go wrong during execution that cant be
detected at compile time.
3Exception Conditions
- When Java encounters an unusual or problematic
situation it responds by throwing an exception. - This causes the run-time system to halt normal
execution and seek help. - Hopefully the programmer has inserted code to
catch the exception.
4Example
- int offsetx/n is certainly a simple expression
in Java. What happens if n, somehow, has the
value of 0?
5Exception Subclasses
- There are around fifty-three kinds of exceptions
in Java.
6Exception Hierarchy
Object
Throwable
Error
Exception
IllegalAccessException
RuntimeException
IOException
7- Exceptions are used to indicate situations that
you will, should, be able to handle in your
program.
8Handling Exceptions
- try
- //Code where an exception may occur
-
- catch (ExceptionType e)
- //Code to handle the exception
9Example (1)
- try
- int offsetx/n
-
- catch (ExceptionType e)
- offset10
-
- //Execution continues from here after handling
exception.
10Example (2)
public void delete() String outgetString(Ente
r string to delete) int posOuttext.indexOf(ou
t) try texttext.substring(0,posOut)text.su
bstring(posOutout.length()) catch
(StringIndexOutOfBoundsException e)
displayResult(String not found - no deletion
occurred.)
11Example (3)
public class TrivialApplication public
static void main(String args) String
scores"34", "34.5", "12", "23.5","45.6", "23",
"10" int sum0 for (int i0
iltscores.length i) try sumInteger.
parseInt(scoresi) catch
(NumberFormatException e) System.out.prin
tln( "Summing the integer values gives "sum
)
12Example (4)
public class TrivialApplication public
static void main(String args) String
scores"34", "34.5", "12", "23.5","45.6", "23",
"10" int sumInt0 float sumFloat0.0f fo
r (int i0 iltscores.length i) try
sumIntInteger.parseInt(scoresi)
catch (NumberFormatException e)
sumFloatFloat.valueOf(scoresi).floatValu
e() System.out.println( "Summing the
integer values gives "sumInt ) System.out.prin
tln( "Summing the float values gives "sumFloat
)
13Example (5)
public class TrivialApplication public
static void main(String args) String
scores"34", "34.5", "12", "23.5","45.6",
"fred","23", "10" int sumInt0 float
sumFloat0.0f for (int i0 iltscores.length
i) try sumIntInteger.parseInt(score
si) catch (NumberFormatException e1)
try sumFloatFloat.valueOf(scoresi)
.floatValue() catch (NumberFormatExcept
ion e2) System.out.println(
"Summing the integer values gives "sumInt
) System.out.println( "Summing the float
values gives "sumFloat )
14Details
- A try block must be followed by one or more catch
clauses. - If no exception is raised in the try block, the
catch blocks are skipped. - If an exception is raised in the try block
control passes to the first catch clause with an
argument matching the exception thrown.
15Example
- try
- //code may generate different types of
exceptions -
- catch (StringIndexOutOfBoundException e)
- //code to handle the exception
-
- catch (ArithmeticException e)
- //code to handle the exception
-
- catch (NullPointerException e)
- //code to handle the exception
-
16Exception Propagation
- When an exception is raised in a try block the
system first looks for an associated catch clause
to handle it. If none is found then the system
looks at the next level of nesting. This
continues until the Java system itself is reached.
17Exception Types
- Checked
- Exceptions that are checked at compile time.
- Unchecked
- Also called runtime exceptions. Only detectable
at runtime.
18Extending Exceptions
- A new exception is defined by deriving a new
class from the Exception class or one of its
descendants.
19Generating Exceptions
- The programmer attempts to capture errors that
may occur during program execution. Exceptions
are one way of dealing with classes of errors.
In Java, if you encounter a particular type of
error you can throw an exception.
20Example
public class TrivialApplication public
static void main(String args) final int
MIN20, MAX50 OutOfRangeException except new
OutOfRangeException (Value out of Range) int
valueKeyboard.getInt() if (valueltMIN
valuegtMAX) throw except class
OutOfRangeException extends Exception
OutOfRangeException (String message)
super(message)
21throws
- Any method that may throw an exception much
acknowledge it in the declaration. - public void methodName() throws Exception
22finally
- The finally block is optional, but is placed
after the last of the catch blocks. - try
- //statements
-
- catch (AnException e) //handle AnException
- catch (DifferentException e) //handle
DifferentException - finally //executed under all conditions
23finally (2)
- Java guarantees a finally block will be executed
regardless of whether an exception is thrown. - finally blocks are good for routines that use
resources so those resources can be released.
24Finally
- If no exception occurs, the catch handlers are
skipped and control proceeds to the finally
block. - If an exception occurs, the try block is skipped
and the catch blocks handle the exception, then
control passes to the finally block. - If an exception occurs and no catch block handles
the exception the finally block is executed, then
the exception is passed up the call chain.