Lecture_10_Exception
Lecture_10_Exception
• finally Block
• Stack Unwinding
• Chained Exceptions
• Custom Exception
2
testException.java
Numerator: 10
Denominator: 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at testException.divideException(testException.java:101)
at testException.process(testException.java:147)
at testException.main(testException.java:164)
3
Why using exception?
• Prior example assumed that the user would input a proper integer.
- Users sometimes make mistakes and input incorrect or wrong type of values.
- Your program is terminated.
• Something out of the ordinary may happen. Using “if…else” statements can be
cumbersome to handle them.
- Mix the main logic with exception handling.
4
Exception
• Exception - an indication of a problem that occurs during a program’s execution.
- The name “exception” implies that the problem occurs infrequently.
5
Exception stack trace
• Stack trace information is displayed when an exception occurs and is not handled.
• Information includes:
- The name of the exception in a descriptive message that indicates the problem
that occurred
- The method-call stack (i.e., the call chain) at the time it occurred. Represent
the path of execution that led to the exception method by method.
6
Different exceptions
• ArrayIndexOutOfBoundsException occurs when an attempt is made to
access an element past either end of an array.
• ClassCastException occurs when an attempt is made to cast an object
that does not have an is-a relationship with the type specified in the cast
operator.
• A NullPointerException occurs when a null reference is used where an
object is expected.
• Only classes that extend Throwable (package java.lang) directly or
indirectly can be used with exception handling.
- Throwable is the superclass of all errors and exceptions in Java.
7
Java exception hierarchy
8
Java exception hierarchy
• Class Throwable has two subclasses: Exception and Error.
• Class Error and its subclasses represent abnormal situations that happen
in the JVM.
- These should not be caught by applications.
- Applications usually cannot recover from Errors.
9
Java exception hierarchy
• Exception classes inherit directly or indirectly from class Exception,
forming an inheritance hierarchy.
- Can extend this hierarchy with your exception classes.
• Figure 11.4 shows only a small portion of the inheritance hierarchy for the
class Throwable (a subclass of Object).
- Only Throwable objects can be used with the try-catch mechanism.
10
Checked vs. unchecked exceptions
• For the purpose of compile-time checking of exceptions, Throwable and any
subclass of Throwable that is not also a subclass of either RuntimeException
or Error are regarded as checked exceptions.
- Otherwise, it is an unchecked exception.
• Checked exceptions
- If a method throws a checked exception, then it must either handle the
exception or it must specify the exception using the throws keyword.
• Unchecked exceptions
- Not forced by the compiler to either handle or specify the exception.
11
CheckedException.java
12
testException.java
13
try…catch block
A Java program can handle an exception using a try…catch block.
Syntax:
try {
statements that may throw exceptions
}
catch(Exception e) {
statements that handle the exception
}
14
try…catch block
• try block begins with the keyword try and encloses
- code that should execute if no exception occurs, i.e., the main logic.
- code that throws an exception when an exception occurs.
• catch block (also called a catch clause or exception handler) catches and
handles an exception. Begin with the keyword catch followed by an exception
parameter in parentheses and a block of code enclosed in curly braces to
handle the exception.
• The exception parameter identifies the exception type the handler can process.
• The code executes if the specified exception occurs.
• Multiple catch blocks can follow a try block.
15
try…catch block
• When an exception occurs in a try block, the catch block, whose type
matches the type of the exception, executes.
• The parameter’s name enables the catch block to interact with a caught
exception object.
16
testException.java
Numerator: 10
Denominator: 0
Exception: / by zero
17
Multiple catch blocks
• When a try block may throw various exceptions, a different exception
handler can be defined in each catch block after the try block.
• The first one whose type matches the type of the exception that occurred
will be executed.
Syntax:
try {
statements that may throw different exceptions
}
catch(exceptionType1 e1) {
handling statements for type1 exception
}
catch(exceptionType2 e2) {
handling statements for type2 exception
}
18
testException.java
19
Example - multiple exception handlers
catch (ArrayIndexOutOfBoundsException e) {
if(idx == -100)
done = true;
else
System.out.println("Index out of bounds. " + e);
}
catch (InputMismatchException e) {
System.out.println("Wrong input type. " + e);
keyIn.next();
}
catch (Exception e) {
System.out.println("Another exception. " + e);
}
}
}
20
Multi-types
• If the bodies of several catch blocks are identical, you can use the multi-
catch feature to catch those exception types in a single catch handler
and perform the same task.
Syntax
try {
statements that may throw different exceptions
}
catch (Type1 | Type2 | Type3 e) {
handling statements
}
21
testException.java
System.out.print("Numerator: ");
int num = keyIn.nextInt();
System.out.print("Denominator: ");
int denom = keyIn.nextInt();
23
Exception handling
• If an exception occurs in a try block, the try block terminates immediately and
program control transfers to the first matching catch block.
• After the exception is handled, control resumes after the last catch block.
• The local variables in a try and a catch block only can be used inside the block.
• If no exceptions are thrown in a try block, the catch blocks are skipped, and
control continues with the first statement after the catch blocks.
24
Java exception hierarchy
• When a catch handler is written to catch objects of an exception class, it
can also catch all objects of that class’s subclasses.
• If multiple catch blocks match a particular exception type, only the first
matching catch block executes.
25
Example - exception hierarchy
int idx = 0;
try {
idx = keyIn.nextInt();
System.out.println("data[" + idx + "]=" + data[idx]);
}
catch (Exception e) {
System.out.println("Another exception. " + e);
}
catch (ArrayIndexOutOfBoundsException e) { errors: exception
if(idx == -100) ArrayIndexOutOfBoundsException
done = true; and InputMismatchException have
else already been caught
System.out.println("Index out of bounds. " + e);
}
catch (InputMismatchException e) {
System.out.println("Wrong input type. " + e);
keyIn.next(); //Jump over the string
}
26
Uncaught exception
• For which there are no matching catch blocks.
• An uncaught exception causes the application to terminate early.
• This does not always occur because of uncaught exceptions.
• Java uses a multithreaded model of program execution.
- Each thread is a concurrent activity. One program can have many threads.
- If a program has only one thread, an uncaught exception will cause the
program to terminate.
- If a program has multiple threads, an uncaught exception will
terminate only the thread in which the exception occurred.
27
When to use exception handling
• Exception handling is designed to process synchronous errors, which
occur when a statement executes.
• Common examples:
- out-of-range array indices
- arithmetic overflow
- division by zero
- invalid method parameters
- thread interruption
28
No exception handling
29
finally Block
• The finally block, which starts with the finally keyword, followed by
code enclosed in curly braces, sometimes referred to as the finally
clause, is optional.
• finally block will execute if a try block exits by using a return, break or
continue statement or simply by reaching its closing right brace.
• finally block will not execute if the application exits early from a try
block by calling method System.exit.
30
finally Block
• Because a finally block always executes, it typically contains resource-
release code.
• Suppose a resource is allocated in a try block.
- If no exception occurs, control proceeds to the finally block, which
frees the resource. Control then proceeds to the first statement after
the finally block.
- If an exception occurs, the try block terminates. The program catches
and processes the exception in one of the corresponding catch blocks,
then the finally block releases the resource and control proceeds to the
first statement after the finally block.
- If the program doesn’t catch the exception, the finally block still releases
the resource and an attempt is made to catch the exception in a calling
method.
31
testException.java
33
Stack Unwinding
• Stack unwinding: when an exception is thrown but not caught in a
particular scope, the method-call stack is “unwound”.
• An attempt is made to catch the exception in the next outer try block.
• All local variables in the unwound method go out of scope and control
returns to the statement that originally invoked that method.
• If a try block does not enclose that statement or if the exception is not
caught, stack unwinding occurs again.
34
testException.java
35
Example - stack unwinding
public void method2() throws Exception {
method3();
}
36
Chained exceptions
• Sometimes a method responds to an exception by throwing a different
exception type that is specific to the situation.
- If a catch block throws a new exception, the original exception’s
information and stack trace are lost.
37
testException.java
38
Example - chained exceptions
39
Custom exception
• Sometimes it’s useful to declare your exception classes that are
specific to the problems that can occur when another programmer
reuses your code.
40
testException.java
43
Exception Summary
• Exceptions are a good mechanism to flag input data that does not pass
validation.
- That said, it is good software engineering and security practice to allow
for input data that may fail validation.
- This is especially so if the source of the input data is a user or system
that you have no control over.
- We can also create our exception classes, instantiate and throw them.
• The finally clause is an addition to the try-catch blocks we’ve seen so far and contains
statements that we always want to have executed regardless of whether there is an
exception or not.
45