Introduction To Exceptions in Java
Introduction To Exceptions in Java
Introduction To Exceptions in Java
Exceptions in Java
Recall the Array Implementation of a
Stack
0 1 2 3 4 5 6 7
…
stack
5
s
top
3-2
Incorrect implementation of the pop
operation in class ArrayStack
public T pop( ) {
top--;
T result = stack[top];
stack[top] = null;
return result;
}
3-3
Let the Main Method be This
6
Exceptions
• These erroneous situations throw an exception
• Exceptions can be thrown by the Java virtual
machine or by the program
7
The Error Messages Contain Useful Information
public class ArrayStack<T> implements StackADT<T> {
.
.
.
public T pop( ) {
top--;
87: T result = stack[top];
stack[top] = null;
return result;
}
The error message tells us where the error is:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: -1
at ArrayStack.pop(ArrayStack.java:87)
at TestStack.main(TestStack.java:6) 3-8
The Error Messages Contain Useful Information
public class TestStack {
public T pop( ) {
if (isEmpty( ))
what should we do?
top--;
T result = stack[top];
stack[top] = null;
return result;
}
3-10
We Can Fix the Problem by Using Java Exceptions
3-11
Notice the specification of where exceptions are thrown in
the Stack ADT
public interface StackADT<T> {
// Adds one element to the top of this stack
public void push (T dataItem);
// Removes and returns the top element of this stack
public T pop( ) throws EmptyCollectionException;
// Returns the top element of this stack
public T peek( ) throws EmptyCollectionException;
// Returns true if this stack is empty
public boolean isEmpty( );
// Returns the number of elements in this stack
public int size( );
// Returns a string representation of this stack
public String toString( );
}
3-12
Ignorig Exceptions
14
Catching Exceptions
16
Catching Exceptions
17
Catching Exceptions
• Exception propagation continues until
– The exception is caught and handled
– Or until it is propagated out of the main method,
resulting in the termination of the program
18
Catch Blocks
19
A Try-Catch Example with Multiple
Catch Statements
The try-catch syntax:
try {
code
}
catch(exception1 e) {statements}
catch(exception2 e) {statements}
catch(exception3|exception4 e){statements}
20
Re-Throwing Exceptions
public class TestStack {
private static void helper (ArrayStack<String> s) throws
EmptyStackException {
String line = s.pop();
Method helper re-throws
... the exception thrown
} by pop()
22
Some Java Error and Exception Classes
23
Runtime Errors
• Java differentiates between runtime errors
and exceptions
– Errors are unrecoverable situations, so
the program must be terminated
• Example: running out of memory
24
Exceptions
Exception: an abnormal or erroneous situation at
runtime
Examples:
• Division by zero
• Array index out of bounds
• Null pointer exception
i = size / 0;
26
public class ExceptionExample { private static void method2(String str) {
private static int x = 1; if (str.length() > 0) ++x;
private static String s = “”; else
public static void main(String[] args) { throw new Exception1(“Empty string”);
try { s = “hello”;
method1(2); throw new Exception2(“Long string”);
method1(1);
}
x = x + 3;
}
catch (Exception1 e) {x = 0;}
catch (Exception2 ex) {x = x + 5;}
System.out.println(x+”, “+s);
}
private static void method1(int param) throws Exception1, Exception2 {
try {
if (param == 1) method2(“hello”);
else method2(s);
++x;
}
catch (Exception1 e) {
System.out.println(e.getMessage()); Execute by hand this
s = “hi”; code. What is printed
} by the program?
}
Checked and Unchecked Exceptions
• Checked exceptions are checked by the
compiler
• Unchecked exceptions are not
28
Example: Checked Exception
import java.io.*;
class Main {
public static void main(String[] args) {
try {
FileReader file = new FileReader(“test.txt");
BufferedReader fileInput = new BufferedReader(file);
System.out.println(fileInput.readLine());
fileInput.close();
}
catch (FileNotFoundException e) { ... }
catch (IOException e) { ... }
}
}
29
Example: Checked Exception
import java.io.*;
class Main {
public static void main(String[] args) {
FileReader file = new FileReader(“test.txt");
BufferedReader fileInput = new BufferedReader(file);
System.out.println(fileInput.readLine());
fileInput.close();
}
}
The compiler gives the error:
Main.java:5: error: unreported exception FileNotFoundException; must be
caught or declared to be thrown
FileReader file = new FileReader(“test.txt”);
30
Example: UnChecked Exception
class Main {
32
Finally Block
The finally block always executes when the try
block exits, whether an exception was thrown or not
(even if the exception was not caught by any of the
catch statements!)
The finally block is executed even if there is a
return statement inside the try or catch blocks or if
a new exception is thrown.
33
No finally Block
PrintWriter out;
try {
out = new PrintWriter(new FileWriter("OutFile.txt"));
out.println(“Data”);
int x = 5 / 0;
}
catch(FileNotFoundException e) {…}
catch(IOException e) {…}
if (out != null) out.close();