8/24/2011

Mục tiêu của bài học

(cid:61550) Giải thích về ngoại lệ là gì và mô tả các lợi ích của việc xử lý ngoại lệ hướng đối tượng

Bộ môn Công nghệ Phần mềm Viện CNTT & TT Trường Đại học Bách Khoa Hà Nội

(cid:61550) Giải thích được mô hình xử lý ngoại lệ (cid:61550) Sử dụng khối try/catch/finally để bắt và xử lý

ngoại lệ trong Java

(cid:76)(cid:7852)(cid:80)(cid:32)(cid:84)(cid:82)(cid:204)(cid:78)(cid:72)(cid:32)(cid:72)(cid:431)(cid:7898)(cid:78)(cid:71)(cid:32)(cid:272)(cid:7888)(cid:73)(cid:32)(cid:84)(cid:431)(cid:7906)(cid:78)(cid:71) Bài 08. Ngoại lệ và xử lý ngoại lệ

(cid:61550) Hiểu và biết cách sử dụng ủy nhiệm ngoại lệ (cid:61550) Biết cách tạo ra và sử dụng ngoại lệ tự định

nghĩa

2

Nội dung

Nội dung

1. Ngoại lệ 2. Bắt và xử lý ngoại lệ 3. Ủy nhiệm ngoại lệ 4. Tạo ngoại lệ tự định nghĩa

1. Ngoại lệ 2. Bắt và xử lý ngoại lệ 3. Ủy nhiệm ngoại lệ 4. Tạo ngoại lệ tự định nghĩa

3

4

1.1. Ngoại lệ là gì?

1.1. Ngoại lệ là gì? (2)

(cid:61550) Exception = Exceptional event

(cid:69)(cid:82)(cid:82)(cid:79)(cid:82)(cid:32)(cid:33)(cid:33)

Ví dụ:

5

6

1

8/24/2011

1.2. Cách xử lý lỗi truyền thống

Ví dụ

int devide(int num, int denom, int *error) {

(cid:61550) Viết mã xử lý tại nơi phát sinh ra lỗi (cid:61550) Truyền trạng thái lên mức trên

if (denom != 0){ error = 0; return num/denom;

} else {

error = 1; return 0;

}

}

7

8

Nhược điểm

Nội dung

1. Ngoại lệ 2. Bắt và xử lý ngoại lệ 3. Ủy nhiệm ngoại lệ 4. Tạo ngoại lệ tự định nghĩa

9

10

2.1. Mục đích của xử lý ngoại lệ

2.1. Mục đích của xử lý ngoại lệ (2)

(cid:61550) Khi xảy ra ngoại lệ, nếu không có cơ chế xử

lý thích hợp?

………… IF B IS ZERO GO TO ERROR C = A/B PRINT C GO TO EXIT

ERROR:

DISPLAY “DIVISION BY ZERO”

EXIT:

END

11

12

Khối xử lý lỗi

2

8/24/2011

2.2. Mô hình xử lý ngoại lệ

2.2. Mô hình xử lý ngoại lệ (2)

(cid:61550) Hướng đối tượng

(cid:61550) 2 cách

13

14

2.3. Xử lý ngoại lệ trong Java

2.3. Xử lý ngoại lệ trong Java (2)

(cid:61550) Java có cơ chế xử lý ngoại lệ rất

(cid:61550) Các từ khóa

mạnh

(cid:61550) try

(cid:61550) catch

(cid:61550) finally (cid:61550) throw

(cid:61550) throws

15

16

Ví dụ không xử lý ngoại lệ

2.3.1. Khối try/catch

class NoException {

(cid:61550) Khối try ... catch:

public static void main(String args[]) {

try {

// Doan ma co the gay ngoai le

String text = args[0]; System.out.println(text);

}

}

catch (ExceptionType e) {

}

// Xu ly ngoai le

}

17

18

3

8/24/2011

Ví dụ có xử lý ngoại lệ

Ví dụ chia cho 0

19

20

public class ChiaCho0Demo { public static void main(String args[]){ class ArgExceptionDemo { try { public static void main(String args[]) { try { int num = calculate(9,0); System.out.println(num); String text = args[0]; System.out.println(text); } catch(Exception e) { System.err.println("Co loi xay ra: " + e.toString()); } catch(Exception e) { } System.out.println(“Hay nhap tham so khi chay!"); } } static int calculate(int no, int no1){ } } int num = no / no1; return num; } }

a. Lớp Throwable

2.3.2. Cây phân cấp ngoại lệ trong Java

(cid:61550) Một số phương thức cơ bản?

21

22

public class StckExceptionDemo {

b. Lớp Error

(cid:61550) Các lớp con:

(cid:61550) VirtualMachineError: InternalError,

OutOfMemoryError, StackOverflowError, UnknownError

(cid:61550) ThreadDeath (cid:61550) LinkageError:

(cid:61550) IncompatibleClassChangeError

(cid:61550) AbstractMethodError, InstantiationError, NoSuchFieldError,

(cid:61550) …

(cid:61550) …

23

24

public static void main(String args[]){ try { int num = calculate(9,0); System.out.println(num); } catch(Exception e) { Co loi xay ra :" System.err.println(“ + e.getMessage()); e.printStackTrace(); } } static int calculate(int no, int no1) { int num = no / no1; return num; } NoSuchMethodError… }

4

8/24/2011

c. Lớp Exception

Một số lớp con của Exception

(cid:61550) ClassNotFoundException, SQLException (cid:61550) java.io.IOException:

(cid:61550) FileNotFoundException, EOFException…

(cid:61550) RuntimeException:

(cid:61550) Chứa các loại ngoại lệ nên/phải bắt và xử lý hoặc ủy nhiệm. (cid:61550) RuntimeException?

(cid:61550) NullPointerException, BufferOverflowException (cid:61550) ClassCastException, ArithmeticException (cid:61550) IndexOutOfBoundsException:

(cid:61550) ArrayIndexOutOfBoundsException, (cid:61550) StringIndexOutOfBoundsException…

(cid:61550) IllegalArgumentException:

(cid:61550) NumberFormatException, InvalidParameterException…

(cid:61550) …

25

26

2.3.3. Khối try – catch lồng nhau

Ví dụ IOException

try {

import java.io.InputStreamReader; import java.io.IOException; public class HelloWorld{

public static void main(String[] args) {

// Doan ma co the gay ra IOException try {

InputStreamReader isr = new

// Doan ma co the gay ra NumberFormatException } catch (NumberFormatException e1) {

InputStreamReader(System.in);

// Xu ly loi sai dinh dang so

try {

} } catch (IOException e2) { // Xu ly loi vao ra }

System.out.print("Nhap vao 1 ky tu: "); char c = (char) isr.read(); System.out.println("Ky tu vua nhap: " + c);

}catch(IOException ioe) { ioe.printStackTrace();

}

}

27

28

}

2.3.4. Nhiều khối catch

(cid:61550) ExceptionType1 phải là lớp con hoặc ngang hàng với ExceptionType2 (trong cây phân cấp kế thừa)

class MultipleCatch1 {

try {

// Doan ma co the gay ra nhieu ngoai

public static void main(String args[]) {

try {

le

} catch (ExceptionType1 e1) {

String num = args[0]; int numValue = Integer.parseInt(num); System.out.println("Dien tich hv la: "

// Xu ly ngoai le 1

+ numValue * numValue);

} catch(Exception e1) {

} catch (ExceptionType2 e2) {

System.out.println("Hay nhap canh cua hv!");

} catch(NumberFormatException e2){

// Xu ly ngoai le 2

System.out.println("Not a number!");

}

} ...

}

}

29

30

5

8/24/2011

class MultiCatch2 {

class MultipleCatch1 {

public static void main( String args[]) {

try {

public static void main(String args[]) {

try {

// format a number // read a file // something else...

String num = args[0]; int numValue = Integer.parseInt(num); System.out.println("Dien tich hv la: "

} catch(IOException e) {

+ numValue * numValue); } catch(ArrayIndexOutOfBoundsException e1) {

System.out.println("I/O error "+e.getMessage();

Hay nhap canh cua hv!");

System.out.println(“

} catch(NumberFormatException e2){

Hay nhap 1 so!");

} catch(NumberFormatException e) {

System.out.println(“

}

System.out.println("Bad data "+e.getMessage();

}

}

} catch(Throwable e) { // catch all

System.out.println("error: " + e.getMessage();}

}

}

31

32

}

2.3.5. Khối finally

... public void openFile(){ try {

// constructor may throw FileNotFoundException FileReader reader = new FileReader("someFile"); int i=0; while(i != -1) {

//reader.read() may throw IOException i = reader.read(); System.out.println((char) i );

} reader.close(); System.out.println("--- File End ---"); } catch (FileNotFoundException e) { No exception //do something clever with the exception

finally

} catch (IOException e) { //do something clever with the exception

try block

}

catch block

finally

33

34

Exception } ...

{

Cú pháp try ... catch ... finally

class StrExceptionDemo static String str; public static void main(String s[]) { try {

try {

// Khoi lenh co the sinh ngoai le

System.out.println(“Truoc ngoai le"); staticLengthmethod(); System.out.println(“Sau ngoai le");

} catch(ExceptionType e) {

// Bat va xu ly ngoai le

} catch(NullPointerException ne) { System.out.println(“Da xay ra loi"); }

} finally {

finally { System.out.println(“Trong finally");

/* Thuc hien cac cong viec can thiet du ngoai le co xay ra hay khong */

}

}

35

36

} static void staticLengthmethod() { System.out.println(str.length()); } }

6

8/24/2011

public void openFile(){

Nội dung

try {

// constructor may throw FileNotFoundException FileReader reader = new FileReader("someFile"); int i=0; while(i != -1) {

//reader.read() may throw IOException i = reader.read(); System.out.println((char) i ); } } catch (FileNotFoundException e) { //do something clever with the exception

1. Ngoại lệ 2. Bắt và xử lý ngoại lệ 3. Ủy nhiệm ngoại lệ 4. Tạo ngoại lệ tự định nghĩa

37

38

} catch (IOException e) { //do something clever with the exception } finally { reader.close(); System.out.println("--- File End ---"); } }

3.1. Ủy nhiệm ngoại lệ

Hai cách làm việc với ngoại lệ

(cid:61550) Ví dụ

public void myMethod(int param) throws

(cid:61550) Xử lý ngay (cid:61550) Ủy nhiệm cho vị trí gọi nó:

Exception{ if (param < 10) {

throw new Exception("Too low!");

} //Blah, Blah, Blah...

}

39

40

public class DelegateExceptionDemo {

3.1. Ủy nhiệm ngoại lệ (3)

(cid:61550) Ví dụ

public static void main(String args[]){ num); “Lan : ” +

class Test {

int num = calculate(9,3); System.out.println( 1 num = calculate(9,0); System.out.println( 2 num); “Lan : ” +

public void myMethod(int param) {

} static int calculate(int no, int no1)

if (param < 10) {

throws ArithmeticException {

throw new RuntimeException("Too

low!");

if (no1 == 0) throw new ArithmeticException("Khong the chia cho 0!");

} //Blah, Blah, Blah...

int num = no / no1; return num;

}

} }

} (cid:61550) (cid:61664) Không lỗi?

41

42

7

8/24/2011

43

44

public class DelegateExceptionDemo { public static void main(String args[]){ public class DelegateExceptionDemo { public static void main(String args[]){ num); “Lan : ” + try { int num = calculate(9,3); 1 System.out.println( num = calculate(9,0); System.out.println( 2 num); “Lan : ” + num); “Lan : ” + } static int calculate(int no, int no1) int num = calculate(9,3); System.out.println( 1 num = calculate(9,0); System.out.println( 2 num); throws Exception { “Lan : ” + } catch(Exception e) { System.out.println(e.getMessage()); if (no1 == 0) throw new } ArithmeticException("Khong the chia cho 0!"); } static int calculate(int no, int no1) int num = no / no1; return num; throws ArithmeticException { } } if (no1 == 0) throw new ArithmeticException("Khong the chia cho 0!"); int num = no / no1; return num; } }

3.1. Ủy nhiệm ngoại lệ (4)

3.2. Lan truyền ngoại lệ

C() tung ngoại lệ

C()

(cid:61550) Ủy nhiệm nhiều hơn 1 ngoại lệ public void myMethod(int tuoi, String ten)

B()

B()

throws ArithmeticException, NullPointerException{

A()

A()

if (tuoi < 18) {

main()

throw new Arithmetic

Chua du tuoi!");

main()

Exception(“

} if (ten == null) {

(cid:61550) Nếu C() gặp lỗi và tung ra ngoại

throw new NullPointer

Thieu ten!");

Exception(“

} //Blah, Blah, Blah...

}

lệ nhưng trong C() lại không xử lý ngoại lệ này, th(cid:236) chỉ còn một nơi có thể xử lý chính là nơi mà C() được gọi, đó là trong phương thức B().

(cid:61550) …

45

46

3.3. Kế thừa và ủy nhiệm ngoại lệ

3.3. Kế thừa và ủy nhiệm ngoại lệ (2)

class Disk { void readFile() throws EOFException {}

(cid:61550) Khi override một phương thức của lớp cha, phương thức ở lớp con không được phép tung ra các ngoại lệ mới

} class FloppyDisk extends Disk { void readFile() throws IOException {} }

class Disk { void readFile() throws IOException {}

47

48

} class FloppyDisk extends Disk { void readFile() throws EOFException {} }

8

8/24/2011

Nội dung

3.4. Ưu điểm của ủy nhiệm ngoại lệ

1. Ngoại lệ 2. Bắt và xử lý ngoại lệ 3. Ủy nhiệm ngoại lệ 4. Tạo ngoại lệ tự định nghĩa

49

50

4949

4. Tạo ngoại lệ tự định nghĩa

Sử dụng ngoại lệ người dùng định nghĩa

public class MyException extends Exception {

public MyException(String msg) {

public class FileExample {

super(msg);

public void copyFile(String fName1,String fName2)

throws MyException

} public MyException(String msg, Throwable cause){

{

if (fName1.equals(fName2))

super(msg, cause);

throw new MyException("File trung ten");

}

// Copy file

}

System.out.println("Copy completed");

}

}

51

52

Sử dụng ngoại lệ người dùng định nghĩa

(cid:61550) Bắt và xử lý ngoại lệ public class Test {

public static void main(String[] args) { FileExample obj = new FileExample(); try {

53

String a = args[0]; String b = args[1]; obj.copyFile(a,b); } catch (MyException e1) { System.out.println(e1.getMessage()); } catch(Exception e2) { System.out.println(e2.toString()); } } }

9