Title: COMP 14 Introduction to Programming
1COMP 14Introduction to Programming
- Exceptions
- Monday, July 24, 2006
2This week
- Today
- Quiz
- Exceptions
- Tuesday
- Review
- Wednesday
- Reading day (no class)
- Thursday
- Final exam 800 1100 am (this room)
- Assignment 7 due at midnight
- If you have a conflict you must inform me and
take the exam BEFORE the scheduled time
3Assignments
- Assignment 6
- We will review tomorrow
- Assignment 7
- Questions?
- Follow examples from Friday and/or book
- Due Thursday, July 27 at midnight
- Grades
4Exception Objectives
- Learn what an exception is
- See how a try/catch block is used to handle
exceptions - Become aware of the hierarchy of exception
classes - Learn about checked and unchecked exceptions
- Learn how to handle exceptions within a program
- Discover how to throw and rethrow an exception
5Exception
- An occurrence of an undesirable situation that
can be detected during program execution. - Examples
- Division by zero.
- Trying to open an input file that does not exist.
- An array index that goes out of bounds.
6Handling Exceptions within a Program
- Can use an if statement to handle an exception.
- However, suppose that division by zero occurs in
more than one place within the same block. - In this case, using if statements may not be the
most effective way to handle the exception.
7Javas Mechanism of Exception Handling
- When an exception occurs, an object of a
particular exception class is created. - Java provides a number of exception classes to
effectively handle certain common exceptions,
such as - Division by zero
- Invalid input
- File not found
8Javas Mechanism of Exception Handling
- Division by zero is
- An arithmetic error.
- Handled by the class ArithmeticException.
- When a division by zero exception occurs, the
program creates an object of the class
ArithmeticException.
9Javas Mechanism of Exception Handling
- When a Scanner object is used to input data into
a program, any invalid input errors are handled
using the class InputMismatchException. - The class Exception (directly or indirectly) is
the superclass of all the exception classes in
Java.
10try/catch/finally Block
- Statements that might generate an exception are
placed in a try block. - The try block
- Might also contain statements that should not be
executed if an exception occurs. - Is followed by zero or more catch blocks.
- A catch block
- Specifies the type of exception it can catch.
- Contains an exception handler.
11try/catch/finally Block
- The last catch block may or may not be followed
by a finally block. - Any code contained in a finally block always
executes regardless of whether an exception
occurs, except when the program exits early from
a try block by calling the method System.exit. - If a try block has no catch block, then it must
have the finally block.
12try/catch/finally Block
13try/catch/finally Block
- If no exception is thrown in a try block, all
catch blocks associated with the try block are
ignored and program execution resumes after the
last catch block. - If an exception is thrown in a try block, the
remaining statements in the try block are
ignored. - The program searches the catch blocks in the
order in which they appear after the try block
and looks for an appropriate exception handler.
14try/catch/finally Block
- If the type of the thrown exception matches the
parameter type in one of the catch blocks, the
code of that catch block executes and the
remaining catch blocks are ignored. - If there is a finally block after the last catch
block, the finally block executes regardless of
whether an exception occurs.
15Order of catch Blocks
- The heading of a catch block specifies the type
of exception it handles. - A catch block can catch either all exceptions of
a specific type or all types of exceptions. - A reference variable of a superclass type can
point to an object of its subclass.
16Order of catch Blocks
- If you declare an exception using the class
Exception in the heading of a catch block, then
that catch block can catch all types of
exceptions because the class Exception is the
superclass of all exception classes. - In a sequence of catch blocks following a try
block, a catch block that declares an exception
of a subclass type should be placed before catch
blocks that declare exceptions of a superclass
type.
17Order of catch Blocks
18Order of catch Blocks
19Order of catch Blocks
20Order of catch Blocks
21Order of catch Blocks
22Javas Exception Class
- class Exception
- Subclass of class Throwable.
- Superclass of classes designed to handle
exceptions. - Various types of exceptions
- I/O exceptions.
- Number format exceptions.
- File not found exceptions.
- Array index out of bounds exceptions.
- Various exceptions categorized into separate
classes and contained in various packages.
23Javas Exception Class
24Javas Exception Class
25Javas Exception Class
26Javas Exception Class
27Javas Exception Class
28Javas Exception Class
29Checked Exceptions
- Any exception that is analyzed by the compiler.
- Example
- FileNotFoundExceptions.
30Unchecked Exceptions
- Exceptions that are not analyzed when the program
compiles - Examples
- Division by zero
- Array index out of bounds
- Syntax
- throws ExceptionType1, ExceptionType2,...
- ExceptionType1, ExceptionType2, and so on are
names of exception classes
31The class Exception and catch blocks
- A reference of a superclass type can point to
objects of its subclass. - You can combine catch blocks using this facility.
32Exceptions Example Code
- public static void exceptionMethod()
- throws InputMismatchException,
- FileNotFoundException
-
- //statements
-
- The method exceptionMethod throws exceptions of
the type InputMismatchException and
FileNotFoundException.
33Rethrowing and Throwing an Exception
- When an exception occurs in a try block, control
immediately passes to one of the catch blocks. - Typically, a catch block does one of the
following - Completely handles the exception.
- Partially processes the exception.
- In this case, the catch block either rethrows the
same exception or throws another exception for
the calling environment to handle the exception. - Rethrows the same exception for the calling
environment to handle the exception.
34Rethrowing and Throwing an Exception
- Useful when
- Catch block catches exception but is unable to
handle it. - Catch block decides exception should be handled
by calling environment. - Allows programmer to provide exception handling
code in one place. - Syntax
- throw exceptionReference
35Rethrowing and Throwing an Exception
import java.util. public class
RethrowExceptionExmp1 static Scanner console
new Scanner(System.in) public static void
main(String args) int number
try
number getNumber() System.out.println("L
ine 5 number number) catch
(InputMismatchException imeRef)
System.out.println("Line 7 Exception "
imeRef.toString())
36Rethrowing and Throwing an Exception
public static int getNumber()
throws InputMismatchException int
num try System.out.print("Line 11
Enter an integer ") num
console.nextInt()
System.out.println() return num
catch (InputMismatchException imeRef)
throw imeRef
37The Method printStackTrace
- Used to determine the order in which the methods
were called and where the exception was handled.
38The Method printStackTrace
import java.io. public class PrintStackTraceExam
ple1 public static void main(String
args) try
methodA() catch (Exception e)
System.out.println(e.toString
() " caught in
main") e.printStackTrace()
39The Method printStackTrace
public static void methodA() throws Exception
methodB() public static void
methodB() throws Exception
methodC() public static void methodC()
throws Exception throw new
Exception("Exception generated "
"in method C")
40The Method printStackTrace
Sample Run java.lang.Exception Exception
generated in method C caught in
main java.lang.Exception Exception generated in
method C at PrintStackTraceExample1.method
C (PrintStackTraceExample1.java31)
at PrintStackTraceExample1.methodB
(PrintStackTraceExample1.java26) at
PrintStackTraceExample1.methodA
(PrintStackTraceExample1.java22) at
PrintStackTraceExample1.main
(PrintStackTraceExample1.java11)
41Exception-Handling Techniques
- Terminate program.
- Output appropriate error message upon
termination. - Fix error and continue.
- Repeatedly get user input.
- Output appropriate error message until valid
value is entered. - Log error and continue.
- Write error messages to file and continue with
program execution.
42To do
- Review Tomorrow
- Email me any topics you would like to cover
- Assignment 7
- Due Thursday, July 27 at midnight
- Follow examples from book / slides
- Final Exam
- Final exam Thursday, 800 1100 am (this room)