11 Exception Handling
11 Exception Handling
Outline
1. Exceptions
OBJECT-ORIENTED PROGRAMMING
2. Catching and handling exceptions
11. EXCEPTION AND EXCEPTION HANDLER
3. Exception delegation
Nguyen Thi Thu Trang
trangntt@soict.hust.edu.vn 4. User-defined exceptions
1 2
3 4
3 4
1
5/10/21
5 6
5 6
7 8
Disadvantages Outline
• Difficult to control all cases 1. Exceptions
• Arithmetic errors, memory errors,…
2. Catching and handling exceptions
• Developers often forget to handle
3. Exception delegation
errors
• Human 4. User-defined exceptions
• Lack of experience, deliberately ignore
7 8
2
5/10/21
9 10
9 10
11 12
11 12
3
5/10/21
13 14
2.2. Models for handling exceptions 2.2. Models for handling exceptions (2)
• Object oriented approach • Exceptions need to be handled at the method that
• Packing unexpected conditions in an object causes the exceptions or delegated to its caller
• When an exception occurs, the object corresponding to the method
exception is created and stores all the detailed information
about the exception
• Providing an efficient mechanism in handling errors
• Separating irregular control threads with regular threads
13 14
15 16
15 16
4
5/10/21
17 18
17 18
19 20
19 20
5
5/10/21
21 22
2.3.2. Exception hierarchical tree in Java 2.3.2. Exception hierarchical tree in Java
Error indicates very
Throwable is a base serious bugs, the
class (ancestor) for all program can not Exception is a basic
exceptions controlled these bugs. class for all the
Object Object
Ex: VirtualMachineError controllable errors.
OutOfMemoryError Ex: ArithmeticException,
Throwable Throwable BufferOverflowException
... ...
21 22
23 24
23 24
6
5/10/21
25 26
25 26
27 28
7
5/10/21
29 30
29 30
31 32
n ExceptionType1 must be a derived class or an level-equivalent
n ExceptionType1 must be a derived class or an level- class of the class ExceptionType2 (in the inheritance hierarchy
equivalent class of the class ExceptionType2 (in the
inheritance hierarchy tree) tree)
class MultipleCatch1 { class MultipleCatch1 {
public static void main(String args[]) public static void main(String args[])
{ {
try { try {
String num = args[0]; String num = args[0];
int numValue = Integer.parseInt(num); int numValue = Integer.parseInt(num);
System.out.println("Dien tich hv la: " System.out.println("Dien tich hv la: "
+ numValue * numValue); + numValue * numValue);
} catch(Exception e1) { } catch(ArrayIndexOutOfBoundsException e1) {
System.out.println("Hay nhap canh cua System.out.println(“Hay nhap canh cua hv!");
hv!"); } catch(NumberFormatException e2){
} catch(NumberFormatException e2){ System.out.println(“Hay nhap 1 so!");
System.out.println("Not a number!"); }
} }
} Error D:\exception java.lang.NumberFormatException }
} has already been caught
31 32
8
5/10/21
class MultiCatch2 { 33 34
public static void main( String args[]) { ...
try { public void openFile(){
// format a number try {
// constructor may throw FileNotFoundException
// read a file FileReader reader = new FileReader("someFile");
// something else... int i=0;
} while(i != -1) {
catch(IOException e) { //reader.read() may throw IOException
i = reader.read();
System.out.println("I/O error "+e.getMessage(); System.out.println((char) i );
} }
catch(NumberFormatException e) { reader.close();
System.out.println("--- File End ---");
System.out.println("Bad data "+e.getMessage();
} catch (FileNotFoundException e) {
} //do something clever with the exception
catch(Throwable e) { // catch all } catch (IOException e) {
System.out.println("error: " + e.getMessage();} //do something clever with the exception
}
}
}
} ...
}
33 34
35 36
2.3.5. finally block The syntax try ... catch ... finally
try {
• Ensure that every necessary tasks are done when an
// May cause exceptions
exception occurs
}
• Closing file, closing socket, connection
• Releasing resource (if neccessary)...
catch(ExceptionType e) {
// Handle exceptions
• Must be done even there is an exception occurring or not. }
finally {
No exception /* Necessary tasks for all cases:
finally exception is raised or not */
}
try block q If there is a block try, there must be a block catch or a
block finally or both
catch block finally
Exception
35 36
9
5/10/21
37 38
37 38
39 40
39 40
10
5/10/21
41 42
41 42
43 44
43 44
11
5/10/21
45 46
public class DelegateExceptionDemo {
public class DelegateExceptionDemo { public static void main(String args[]){
public static void main(String args[]){ int num = calculate(9,3);
int num = calculate(9,3); System.out.println(“Lan 1: ” + num);
System.out.println(“Lan 1: ” + num); num = calculate(9,0);
System.out.println(“Lan 2: ” + num);
num = calculate(9,0); }
System.out.println(“Lan 2: ” + num); static int calculate(int no, int no1)
} throws Exception {
static int calculate(int no, int no1) if (no1 == 0)
throws ArithmeticException { throw new
ArithmeticException(”Cannot divide by 0!");
if (no1 == 0) int num = no / no1;
Compile
throw new return num;
ArithmeticException(”Cannot devide by 0!"); }
int num = no / no1; }
G:\Java Example\DelegateExceptionDemo.java:3: unreported exception java.lang.Exception;
must be caught or declared to be thrown
return num; int num = calculate(9,3);
} ^
G:\Java Example\DelegateExceptionDemo.java:5: unreported exception java.lang.Exception;
} must be caught or declared to be thrown
num = calculate(9,0);
45 46
47 48
47 48
12
5/10/21
49 50
49 50
51 52
3.3. Inheritance and exception delegation 3.3. Inheritance and exception delegation(2)
class Disk {
• Whenoverriding a method of a parent class, void readFile() throws EOFException {}
methods in its child classes can not throw any }
new exception class FloppyDisk extends Disk {
void readFile() throws IOException {} // ERROR!
}
à Overriden method in a child class can only
throw a set of exceptions that are/similar to/ a class Disk {
subset of exceptions thrown from the parent void readFile() throws IOException {}
class. }
class FloppyDisk extends Disk {
void readFile() throws EOFException {} //OK
}
51 52
13
5/10/21
53 54
53
53 54
55 56
55 56
14
5/10/21
57 58
57 58
15