0% found this document useful (0 votes)
4 views

Lecture_10_Exception

The document provides an overview of Java exceptions, including their hierarchy, handling mechanisms such as try-catch blocks, and the use of finally blocks for resource management. It explains the difference between checked and unchecked exceptions, the concept of stack unwinding, and how to create custom exceptions. Additionally, it includes code examples to illustrate exception handling in Java programming.

Uploaded by

urbanatuba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lecture_10_Exception

The document provides an overview of Java exceptions, including their hierarchy, handling mechanisms such as try-catch blocks, and the use of finally blocks for resource management. It explains the difference between checked and unchecked exceptions, the concept of stack unwinding, and how to create custom exceptions. Additionally, it includes code examples to illustrate exception handling in Java programming.

Uploaded by

urbanatuba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Java Exceptions

CSIT213 Java Programming


Overview
• Java exception hierarchy

• Try and Catch Block

• finally Block

• Stack Unwinding

• Chained Exceptions

• Custom Exception

2
testException.java

Example - divide by zero


public void divideException() {
System.out.print("Numerator: ");
int num = keyIn.nextInt();
System.out.print("Denominator: ");
int denom = keyIn.nextInt();

double res = num / denom;


System.out.printf("%d / %d = %.2f\n", num, denom, res);
}

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.

• Exceptions separate the main logic from exception handling.


- Make your code more maintainable.

4
Exception
• Exception - an indication of a problem that occurs during a program’s execution.
- The name “exception” implies that the problem occurs infrequently.

• With Exception handling - a program can continue executing (rather than


terminating) after dealing with a problem.
- Mission-critical or business-critical computing.
- Robust and fault-tolerant programs (i.e., programs that can deal with problems
as they arise and continue executing).

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.

• This information helps you debug the program.

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 Exception and its subclasses represent exceptional situations that


can occur in a Java program
- These can be caught and handled by the application.

• 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

Throws exception clause


• throws clause specifies the exceptions a method might throw.
• Forced for unhandled checked exceptions.
• Appear after the method’s parameter list and before the body.
• Contains a comma-separated list of the exception types.
- May be thrown by statements (manually) in the method’s body or by
methods called (automatically) from there.
• Clients of a method with a throws clause are thus informed that the method
might throw exceptions.
• When a method throws an exception, the method terminates and does not
return a value, and its local variables go out of scope.
• If local variables are references to objects and there are no other references to
those objects, the objects will be deleted by garbage collection.

12
testException.java

Example - throws exceptions clause


public void arrayException1() throws InputMismatchException,
ArrayIndexOutOfBoundsException {
int data[] = {1, 2, 3, 4, 5};

boolean done = false;


while(!done) {
System.out.print("Input an index (-100 exit): ");
int idx = keyIn.nextInt();
System.out.println("data[" + idx + "]=" + data[idx]);
if(idx == -100)
done = true;
}
}

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.

• Use the System.err (standard error stream) object to output error


messages.
- By default, displays data to the command prompt.

16
testException.java

Example - divide by zero


public void divideException1() {
try {
System.out.print("Numerator: ");
int num = keyIn.nextInt();
System.out.print("Denominator: ");
int denom = keyIn.nextInt();

double res = num / denom;


System.out.printf("%d / %d = %.2f\n", num, denom, res);
}
catch(ArithmeticException e) {
System.out.println("Exception: " + e.getMessage());
}
}

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

Example - multiple exception handlers


public void arrayException2() {
int data[] = {1, 2, 3, 4, 5};

boolean done = false;


while(!done) {
System.out.print("Input an index (-100 exit): ");
int idx = 0;
try {
idx = keyIn.nextInt();
System.out.println("data[" + idx + "]=" + data[idx]);
}

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.

• Any number of Throwable types can be specified in a multi-catch.

Syntax
try {
statements that may throw different exceptions
}
catch (Type1 | Type2 | Type3 e) {
handling statements
}

21
testException.java

Example - handling multiple types


public void arrayException3() {
int data[] = {1, 2, 3, 4, 5};

boolean done = false;


int idx = 0;
while(!done && idx != -100) {
System.out.print("Input an index (-100 exit): ");
try {
idx = keyIn.nextInt();
System.out.println("data[" + idx + "]=" + data[idx]);

System.out.print("Numerator: ");
int num = keyIn.nextInt();
System.out.print("Denominator: ");
int denom = keyIn.nextInt();

double res = num / denom;


System.out.printf("%d / %d = %.2f\n", num, denom, res);
}
22
Example - handling multiple types
catch (ArrayIndexOutOfBoundsException | ArithmeticException e){
System.out.println("Exception: " + e.getMessage());
}
catch(InputMismatchException e) {
System.out.println("Exception: " + e.getMessage());
keyIn.next();
}
catch (Exception e) {
System.out.println("Another exception. " + e.getMessage());
}
}
}

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.

• Known as the termination model of exception handling.

- Some languages (not Java) use the resumption model of exception


handling, in which, after an exception is handled, control resumes just
after the throw point.

• 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.

• This enables catch to handle related exceptions polymorphically.

- You can also choose to catch each subclass individually if those


exceptions require different processing.

• If multiple catch blocks match a particular exception type, only the first
matching catch block executes.

• It’s a compilation error to define a catch block that is never executed.

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

• Exception handling is not designed to process problems associated


with asynchronous events

- disk I/O completions

- network message arrivals

- mouse clicks and keystrokes

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 whether or not an exception is thrown in the


corresponding try block.

• 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

Example - finally block


public void arrayException4() {
int data[] = {1, 2, 3, 4, 5};

boolean done = false;


int idx = 0;
while(!done && idx != -100) {
System.out.print("Input an index (-100 exit): ");
try {
idx = keyIn.nextInt();
System.out.println("data[" + idx + "]=" + data[idx]);
System.out.print("Numerator: ");
int num = keyIn.nextInt();
System.out.print("Denominator: ");
int denom = keyIn.nextInt();
double res = num / denom;
System.out.printf("%d / %d = %.2f\n", num, denom, res);
}
32
testException.java

Example - finally block


catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
System.out.println("Exception: " + e.getMessage());
}
catch(InputMismatchException e) {
System.out.println("Exception: " + e.getMessage());
keyIn.next(); //Jump over the string
}
catch (Exception e) {
System.out.println("Another exception. " + e.getMessage());
}
finally {
System.out.println("Finally process something.");
}
}
}

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 encloses that statement, an attempt is made to catch the


exception.

• If a try block does not enclose that statement or if the exception is not
caught, stack unwinding occurs again.

34
testException.java

Example - stack unwinding


public void stackUnwinding() {
try {
method1();
}
catch(Exception e) {
System.out.printf("%s\n", e.getMessage());
e.printStackTrace();
}
}

public void method1() throws Exception {


method2();
}

35
Example - stack unwinding
public void method2() throws Exception {
method3();
}

public void method3() throws Exception {


throw new Exception("Exception from method3()");
}

Exception from method3()


java.lang.Exception: Exception from method3()
at testException.method3(testException.java:210)
at testException.method2(testException.java:206)
at testException.method1(testException.java:202)
at testException.stackUnwinding(testException.java:193)
at testException.process(testException.java:259)
at testException.main(testException.java:273)

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.

• Earlier Java versions provided no mechanism to wrap the original


exception information with the new exception’s information.
- This made debugging such problems particularly difficult.

• Chained exceptions enable an exception object to maintain the complete


stack-trace information from the original exception.
- Pass the exception that causes this exception to constructor

37
testException.java

Example - chained exceptions


public void chainedException() {
try {
methodc1();
}
catch(Exception e) {
e.printStackTrace();
}
} Pass the exception that
causes the current
public void methodc1() throws Exception { exception to constructor
try {
methodc2();
}
catch(Exception e) {
throw new Exception("Exception from methodc1()”, e);
}
}

38
Example - chained exceptions

public void methodc2() throws Exception { Pass the exception that


causes the current
try { exception to constructor
methodc3();
}
catch(Exception e) {
throw new Exception("Exception from methodc2()“, e);
}
}

public void methodc3() throws Exception {


throw new Exception("Exception from methodc3()");
}

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.

• A new exception class must extend an existing exception class to


ensure that the class can be used with the exception-handling
mechanism.

40
testException.java

Example - custom exception


class TemperatureException extends Exception { It is a subclass of Exception
private double degrees;

public TemperatureException(double degrees) {


this.degrees = degrees;
}
Override getMessage()

public String getMessage() {


return "The temperature (" + degrees + "C) isn't in the normal range.";
}

public double getDegrees() {


return degrees;
}
}
41
Example - throws the custom exception
public void measure() throws TemperatureException {
System.out.print("Patient temperature: ");
double degrees = keyIn.nextDouble();
if (degrees > 43 || degrees < 14) {
throw new TemperatureException(degrees);
}
if (degrees >= 38) {
System.out.println("Fever!");
}
else if (degrees < 35) {
System.out.println("Hypothermia!");
}
else
System.out.println("Normal.");
}
42
Example - custom exception handler

public void customException() {


try {
measure();
}
catch(TemperatureException e) {
System.out.println(e.getMessage());
System.out.println("Patient dead: " + e.getDegrees() + " degrees!");
}
catch(Exception e) {
System.out.println("Not a temperature!");
}
}

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.

• Input data that fails validation could be supplied by:


- A malicious user trying to subvert your system
- Another system whose data output has changed, e.g., because of a
configuration change or software upgrade, and whose format is no
longer compatible with yours.

• Validation with exceptions allows you to handle such situations in a way


you control.
44
Exception Summary
• We don’t need to rely on built-in exceptions thrown by code that comes with Java.

- We can throw any exception in our own code.

- We can also create our exception classes, instantiate and throw them.

• If we instantiate and throw a checked exception without handling it in the method


in which we throw it, we must add a throws clause to the method signature to
indicate to the Java compiler that the method may terminate via exception rather
than in the normal way (return).

• 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

You might also like