You are on page 1of 121

Lập trình Java

BÀI 4
Generic, Collection và
Exception trong Java
1
Generic in java

Collection in java

Exception in java

2
Generic in java

3
• Có từ JDK 5
• Cho phép chỉ định kiểu dữ liệu làm việc với một
class, một interface hay một phương thức tại
thời điểm biên dịch
• Ưu điểm
– Kiểm tra dữ liệu chặt chẽ ở Compile-time,
giúp an toàn kiểu dữ liệu (không cho phép lưu
trữ các loại đối tượng khác kiểu được chỉ
định)

4
– Các thuật toán được sử dụng nhiều (reusable), dễ
dàng thay đổi, an toàn dữ liệu và dễ đọc, sử dụng ở
nhiều tình huống khác nhau
• Ví dụ:
– //Chỉ được thêm vào các phần tử Interger
– List<Integer> list = new ArrayList<Integer>(); //Trước
Java 7
– List<Integer> list = new ArrayList<>(); //Từ Java 7

5
• Đặt theo quy ước chung để dễ đọc, dễ bảo trì
• Gợi ý đặt tên
– E: Element (phần tử – trong Collection Framework)
– K: Key (khóa)
– V: Value (giá trị)
– N: Number (kiểu số: Integer, Double, Float, …)
– T: Type (Kiểu Wrapper class: String, Integer, Long,
Float, …)
– S, U, V,…:được sử dụng để đại diện cho các kiểu dữ
liệu (Type) thứ
6
7
8
9 9
10 10
11 11
12 12
Collection in java

13
v ArrayList sử dụng một mảng động để lưu trữ các
phần tử.
v Khai báo một ArrayList
• ArrayList al=new ArrayList();
• ArrayList<String> al =new ArrayList<String>();

14 9/30/15
v Thêm 1 phần tử:
• add(Object);
• add(index, Object)
class TestCollection2{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add(”HTTT");
al.add(”CNPM");
al.add(”MMT");
al.add(”KHMT");
for(String obj:al)
System.out.println(obj);
}
15 9/30/15
• remove(Object);
• remove(index)

class TestCollection2{
public static void main(String args[]){ ArrayList<String>
al=new ArrayList<String>(); al.add(”HTTT");
al.add(”CNPM");
al.add(”MMT");
al.add(”KHMT");

al.remove(1);
for(String obj:al)
System.out.println(obj);
}
16 9/30/15
• set(int index, Object);

• class TestCollection2{
• ArrayList<String>
public static void main(String
al=new args[]){
ArrayList<String>();
al.add(”HTTT");
al.add(”CNPM");
al.add(”MMT");
al.add(”KHMT");
al.set(1,KTMT);
for(String obj:al)
System.out.println(obj);
}
17 9/30/15
• int indexOf(Object);

• class TestCollection2{
• ArrayList<String>
public static void main(String
al=new args[]){
ArrayList<String>();
al.add(”HTTT");
al.add(”CNPM");
al.add(”MMT");
al.add(”KHMT");
int i=indexOf (“HTTT”);
System.out.print(“Vi tri lấy được”+i);
}

18 9/30/15
• Object get(int index);

• class TestCollection2{
• ArrayList<String>
public static void main(String
al=new args[]){
ArrayList<String>();
al.add(”HTTT");
al.add(”CNPM");
al.add(”MMT");
al.add(”KHMT"); String
str=al.get (0);
System.out.print(“Phần tử lấy được”+str);
}

19 9/30/15
• int obj.size();

• class TestCollection2{
• ArrayList<String>
public static void main(String
al=new args[]){
ArrayList<String>();
al.add(”HTTT");
al.add(”CNPM");
al.add(”MMT");
al.add(”KHMT"); int
num=al.size();
System.out.print(“Số phần tử”+num);
}

20 9/30/15
• obj.clear();

class TestCollection2{
public static void main(String args[]){ ArrayList<String>
al=new ArrayList<String>(); al.add(”HTTT");
al.add(”CNPM");
al.add(”MMT");
al.add(”KHMT"); al.clear();
}

21 9/30/15
• ArrayList.addAll(ArrayList);

ArrayList<String> al=new ArrayList<String>();


al.add("Ravi");
al.add("Vijay");
al.add("Ajay");

ArrayList<String> al2=new ArrayList<String>();


al2.add("Sonoo");
al2.add("Hanumat");

al.addAll(al2);

22 9/30/15
• ArrayList.removeAll(ArrayList);

ArrayList<String> al=new ArrayList<String>();


al.add("Ravi");
al.add("Vijay");
al.add("Ajay");

ArrayList<String> al2=new ArrayList<String>();


al2.add("Ravi");
al2.add("Hanumat");

al.removeAll(al2);

23 9/30/15
• ArrayList.retainAll (ArrayList);

ArrayList<String> al=new ArrayList<String>();


al.add("Ravi");
al.add("Vijay");
al.add("Ajay");

ArrayList<String> al2=new ArrayList<String>();


al2.add("Ravi");
al2.add("Hanumat");

al.retainAll(al2);

24 9/30/15
class TestCollection2{
public static void main(String args[]){
ArrayList<SinhVien> al=new ArrayList<SinhVien>();

25 9/30/15
v Dùng danh sách liên kết đơn để lưu các đối tượng
v Khai báo:
LinkedList<String> L =new LinkedList<String>();

26 9/30/15
v void add(Object)

public static void main(String args[]){


LinkedList<String> al=new
LinkedList<String>(); al.add(”Mai");
al.add(”Nhung");
al.add(”Nhi");
al.add(”Lan");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}

27 9/30/15
v void add(index, Object)

public static void main(String args[]){


LinkedList<String> al=new
LinkedList<String>(); al.add(”Mai");
al.add(”Nhung");
al.add(”Nhi");
al.add(2,”Lan"); Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}

28 9/30/15
v boolean list1.addAll(ArrayList);

LinkedList<String> llistobj = new LinkedList<String>();


ArrayList<String> arraylist= new ArrayList<String>();
arraylist.add("String1");
arraylist.add("String2"); llistobj.addAll(arraylist);

29 9/30/15
v boolean list1.addAll(index, ArraList)

LinkedList<String> llistobj = new LinkedList<String>();


ArrayList<String> arraylist= new ArrayList<String>();
arraylist.add("String1");
arraylist.add("String2"); llistobj.addAll(1,arraylist);

30 9/30/15
v void addFirst(Object)

public static void main(String args[]){


LinkedList<String> al=new
LinkedList<String>(); al.add(”Mai");
al.add(”Nhung");
al.add(”Nhi");
al.addFirst(”Lan"); Iterator<String>
itr=al.iterator(); while(itr.hasNext()){
System.out.println(itr.next());
}

31 9/30/15
v void addLast(Object)

public static void main(String args[]){


LinkedList<String> al=new
LinkedList<String>(); al.add(”Mai");
al.add(”Nhung");
al.add(”Nhi");
al.addLast(”Lan"); Iterator<String>
itr=al.iterator(); while(itr.hasNext()){
System.out.println(itr.next());
}

32 9/30/15
v Object clone()

Object str= llistobj.clone(); System.out.println(str);

33 9/30/15
v Lấy tại vị trí: Object get(int index)
v Lấy đầu: Object getFirst();
v Lấy cuối: Object getLast();

public static void main(String args[]){


LinkedList<String> al=new LinkedList<String>();
al.add(”Mai");
al.add(”Nhung");
al.add(”Nhi"); String str=al.get(1);
System.out.println(str);
}

34 9/30/15
v Lấy tại vị trí: Object get(int index)
v Lấy đầu: Object getFirst();
v Lấy cuối: Object getLast();

public static void main(String args[]){


LinkedList<String> al=new LinkedList<String>();
al.add(”Mai");
al.add(”Nhung");
al.add(”Nhi"); String str=al.get(1);
System.out.println(str);
}

35 9/30/15
v int indexOf(Object);

public static void main(String args[]){


LinkedList<String> al=new
LinkedList<String>(); al.add(”Mai");
al.add(”Nhung");
al.add(”Nhi");
int index= al.indexOf(”Nhi"); System.out.print(“Vi
tri lấy được”+index);
}

36 9/30/15
v Xóa đầu: Object remove();
v Xóa tại vị trí: Object remove(int index);
v Xóa phần tử có nội dung:Object remove(Object);
v Xóa đầu: removeFirst();
v Xóa cuối: removeLast();

public static void main(String args[]){


LinkedList<String> al=new LinkedList<String>();
al.add(”Mai");
al.add(”Nhung");
al.add(”Nhi");
al.remove(“Nhung”);
}
37 9/30/15
v Object set(index, Object);

public static void main(String args[]){


LinkedList<String> al=new
LinkedList<String>(); al.add(”Mai");
al.add(”Nhung");
al.add(”Nhi");
al.set(2,”Khanh”);
}

38 9/30/15
v int size();

public static void main(String args[]){


LinkedList<String> al=new
LinkedList<String>(); al.add(”Mai");
al.add(”Nhung");
al.add(”Nhi");
int size=al.size();
System.out.print(“Số phần tử trong list:”+size);
}

39 9/30/15
v void clean()

public static void main(String args[]){ LinkedList<String>


al=new LinkedList<String>(); al.add(”Mai");
al.add(”Nhung");
al.add(”Nhi"); al.clear();
}

40 9/30/15
Để lấy thời gian trong Java ta dung lớp Date:

Date d=new Date(); System.out.print(d.toString());


//Mon Sep 21 16:32:15 GMT+07:00 2015

41 9/30/15
v Ta dùng lớp: SimpleDateFormat để định dạng thời gian

Date d=new Date();


SimpleDateFormat df= new SimpleDateFormat(“M-d-yyyy");
Object oj=df.format(d);
System.out.print("Ngay thang nam:"+oj);

Các định dạng được tra cứu trong bảng 1

42 9/30/15
Date d=new Date();
String strDate= String.format("Ngay thang nam:%td-
%<tm-%<tY",d);
System.out.println(strDate);
//Ngay thang nam:21-09-2015

Các định dạng được tra cứu trong bảng 2

43 9/30/15
Date d = new Date(); int ngay=d.getDate();
int thang=d.getMonth(); int
nam=d.getYear(); nam+=1900;
System.out.println("Ngay lay duoc:"+ngay);
System.out.println("Thang lay duoc:"+thang);
System.out.println("Nam lay duoc:"+nam);

44 9/30/15
SimpleDateFormat formatter = new SimpleDateFormat("dd/
MM/yyyy");
String dateInString = "07/06/2013";
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
ngay=date.getDate(); System.out.println("Ngay doi tu
chuoi:"+ngay);

45 9/30/15
v Cài đặt lớp mảng 1 chiều
• Nhập mảng 1 chiều
• Xuất mảng một chiều
• Tim một phần tử trong mảng
• Đếm theo một tiêu chí nào đó
• Xóa 1 phần tử
• Tìm max
• Tìm min
• Sắp xếp tăng

46 9/30/15
v Cài lớp Quản lý sinh viên biết rằng thông tin của
một sinh viên như sau: tên, mã số sinh viên, điểm
trung bình
v Lớp ngày, tháng năm: nhập vào một ngày: cho
biết ngày thứ mấy trong tuần
v Cài lớp mảng 2 chiều:
• Tổng, tích hai mảng
v Lớp số phức:
v Lớp giờ phút giây:
• Khoảng cách giữa 2 thời gian

47 9/30/15
Exception in java

48
² Exception (ngoại lệ): là một sự kiện xảy
ra trong tiến trình thực thi của một
chương trình, nó làm ngưng tiến trình
bình thường của chương trình
² Khi xảy ngoại lệ, nếu không xử lý
chương trình sẽ kết thúc ngay.
² Ví dụ: Lỗi chia chia cho 0, vượt quá kích
thước mảng, lỗi mở tập tin..vv

49
² Mục đích: làm cho chương trình không bị
ngắt đột ngột.
² Có 2 cách để xử lý ngoại lệ:
² Sử dụng các mệnh đề điều kiện kết hợp với
các giá trị cờ
² Sử dụng cơ chế bắt và xử lý ngoại lệ

50
package org.o7planning.tutorial.exception;
public class HelloException {
public static void main(String[] args) {
System.out.println("Three");
// Phép chia này hoàn toàn không có vấn đề.
int value = 10 / 2;
System.out.println("Two");
// Phép chia này cũng vậy
value = 10 / 1;
System.out.println("One");
// Phép chia này có vấn đề, chia cho 0.
// Lỗi đã xẩy ra tại đây.
value = 10 / 0;
// Và dòng code dưới đây sẽ không được thực hiện.
System.out.println(”Chương trình hoàn tất!”);
}
}

51
public class DemoException
{
public static void main (String args [])
{
int tuso, mauso;
double ketqua;
System.out.println ("Chuong trinh tinh phan so: ");
Scanner input = new Scanner (System.in);
System.out.print ("Tu so: ");
tuso = input.nextInt ();
System.out.print ("Mau so: ");
mauso = input.nextInt ();
ketqua=tuso/mauso;
System.out.print ("Ket Qua: " + ketqua);
System.out.print(”Do some things”);
}
}

52
Điều gì xảy ra khi ta nhập mẫu bằng 0
ØSử dụng các mệnh đề điều kiện kết hợp
với các giá trị cờ
ü Cách dùng: Thông qua tham số, giá trị trả
lại hoặc giá trị cờ để viết mã xử lý tại nơi phát
sinh lỗi
ü Hạn chế:
• Làm chương trình thêm rối, gây khó hiểu
• Dễ nhầm lẫn

53
public class Inventory
{
public final int MIN = 0;
public final int MAX = 100;
public final int CRITICAL = 10;
public boolean addToInventory (int amount)
{
int temp;
temp = stockLevel + amount;
if (temp > MAX)
{
System.out.print("Adding " + amount + " item will cause stock ");
System.out.println("to become greater than " + MAX + " units
(overstock)");
return false;
}

54
else
{
stockLevel = stockLevel + amount;
return true;
}
} // End of method addToInventory
:

55
reference1.method1 ()
if (reference2.method2() == false)
return false;

reference2.method2 ()
if (store.addToInventory(amt) == false)
return false;

store.addToInventory (int amt)


if (temp > MAX)
return false;

56
Vấn đề 1: Phương thức
reference1.method1 () chủ có thể quên kiểm tra
if (reference2.method2() == false) điều kiện trả về
return false;

reference2.method2 ()
if (store.addToInventory(amt) == false)
return false;

store.addToInventory (int amt)


if (temp > MAX)
return false;

57
reference1.method1 ()
if (reference2.method2() == false)
return false;

reference2.method2 ()
if (store.addToInventory(amt) == false)
return false;

store.addToInventory (int amt)


Vấn đề 2: Phải sử dụng if (temp > MAX)
1 loạt các phép kiểm tra return false;
giá trị cờ trả về
58
reference1.method1 ()
if (reference2.method2() == false)
return false;

reference.method2 ()
if (store.addToInventory(amt) == false)
?? return false; ??

Vấn đề 3: Phương thức store.addToInventory (int amt)


chủ có thể không biết if (temp > MAX)
cách xử lý khi lỗi xảy ra return false;

59
• Nhược điểm
üKhó kiểm soát được hết các trường hợp
• Lỗi số học, lỗi bộ nhớ,…
üLập trình viên thường quên không xử lý lỗi

60
61
• Exception ()
• Exception (String msg)
• String getMessage () : Lấy thông báo của
Exception
• void printStackTrace (): In ra stack lan
truyền lỗi của Exception

62
• Trong Java, việc xử lý biệt lệ được cài đặt
bên trong một nhánh nhỏ của chương
trình
• Lỗi được xem như những trường hợp
ngoại lệ. Chúng được bắt, ném (catch,
throws) khi có lỗi xảy ra

63
• Cú pháp:
try
{
Đoạn mã có khả năng gây ra ngoại lệ
}
catch (Exception e1)
{
nếu các lệnh trong khối “try” gây ra ngoại lệ thuộc loại e1 thì xử lý ngoại
lệ, nếu không chuyển xuống khối lệnh “catch” tiếp theo
}
catch(Exception e2)
{
Nếu các lệnh trong khối ‘try’ tạo ra ngoại lệ có loại e2, thì thực hiện xử lý
ngoại lệ nếu không chuyển xuống khối 'catch' tiếp theo
64
}
import java.io.*;
class Driver
{
public static void main (String [] args)
{ BufferedReader stringInput;
InputStreamReader characterInput;
String s;
int num;
characterInput = new InputStreamReader(System.in);
stringInput = new BufferedReader(characterInput);

65
try
{
System.out.print(”Nhập một số nguyên");
s = stringInput.readLine();
System.out.println(“Bạn đã nhập..." + s);
num = Integer.parseInt (s);
System.out.println("Converted to an integer..." + num);
}
catch (IOException e)
{
System.out.println(e);
}
catch (NumberFormatException e)
{
: : :
}
}
}
66
try
{
System.out.print("Type an integer: ");
s = stringInput.readLine();
System.out.println("You typed in..." + s);
num = Integer.parseInt (s);
System.out.println("Converted to an integer..." + num);
}

67
try
{
System.out.print("Type an integer: ");
s = stringInput.readLine(); Biệt lệ có thể xảy ra ở
System.out.println("You typed in..." + s); đây
num = Integer.parseInt (s);
System.out.println("Converted to an integer..." + num);
}

68
http://java.sun.com/j2se/1.4.1/docs/api/java/io/BufferedReader.html

public class BufferedReader


{
public BufferedReader (Reader in);
public BufferedReader (Reader in, int sz);
public String readLine () throws IOException;
:
}

69
try
{
System.out.print("Type an integer: ");
s = stringInput.readLine();
System.out.println("You typed in..." + s); Biệt lệ có thể xảy ra ở
num = Integer.parseInt (s); đây
System.out.println("Converted to an integer..." + num);
}

70
• http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Integer.html

public class Integer


{
public Integer (int value);
public Integer (String s) throws NumberFormatException;
: :
public static int parseInt (String s) throws NumberFormatException;
: :
}

71
try
{
System.out.print("Type an integer: ");
s = stringInput.readLine();
System.out.println("You typed in..." + s);
num = Integer.parseInt (s);
System.out.println("Converted to an integer..." + num);
}
catch (IOException e)
{
System.out.println(e);
}
catch (NumberFormatException e)
{
: : :
}
}
}
72
Integer.parseInt (String s)
{
:
:
Driver.main () }
try
{
num = Integer.parseInt (s);
}
:
catch (NumberFormatException e)
{
:
}

73
Integer.parseInt (String s)
{
Người sử dụng không nhập
chuỗi số
Driver.main () }
try
{
num = Integer.parseInt (s);
}
:
catch (NumberFormatException e)
{
:
}

74
Integer.parseInt (String s)
{
NumberFormatException e =
new
Driver.main () } NumberFormatException ();
try
{
num = Integer.parseInt (s);
}
:
catch (NumberFormatException e)
{
:
}

75
Integer.parseInt (String s)
{
NumberFormatException e =
new
Driver.main () } NumberFormatException ();
try
{
num = Integer.parseInt (s);
}
:
catch (NumberFormatException e)
{
:
}

76
Integer.parseInt (String s)
{

Driver.main ()
}
try
{
num = Integer.parseInt (s);
}
:
catch (NumberFormatException e)
{
Biệt lệ sẻ được xử lý ở đây
}

77
catch (NumberFormatException e)
{
: : :
}
}
}

78
catch (NumberFormatException e)
{
System.out.println(e.getMessage());
System.out.println(e);
e.printStackTrace();
}
}
}
79
catch (NumberFormatException e) Nhập vào: ”exception"
{
System.out.println(e.getMessage());
System.out.println(e);
e.printStackTrace();
java.lang.NumberFormatExcept
}
ion: For input string:
} “exception"
}

java.lang.NumberFormatException: For input string: “exception"


at
java.lang.NumberFormatException.forInputString(NumberFormatException.java:
48)
at java.lang.Integer.parseInt(Integer.java:426)
80 at java.lang.Integer.parseInt(Integer.java:476)
at Driver.main(Driver.java:39)
• Là 1 mệnh đề không bắt buộc trong
khối try-catch-finally.
• Dùng để đặt khối lệnh sẽ được thi hành
bất kể biệt lệ có xay ra hay không.

81
Foo.method ()
try {
{
f.method(); }
}

catch
{
}

finally
{
}

82
u l ệnh làm f.method ()
nh m ột câ {

try 1) Thi a biệt lệ 2) Biệt lệ được tạo ra
{ xảy r }
f.method();
}

bắt
c
đượ
i ệt lệ ử lý
catch
3) B i và x
{ lạ
}

4) Thi hành các câu


finally lệnh trong khối finally
{
}
83
phư ơng f.method ()
thi hành 1 h át sinh {
i p
1) Gọ không làm 2) Phương thức thi
try thức
{ hành bình thường
biệt lệ }
f.method();
}

catch
{
} c âu ally
c ác ối fin
ành g kh
hi h tron
T
finally 3) lệnh
{
}
84
class Driver
{
public static void main (String [] args)
{
TCFExample eg = new TCFExample ();
eg.method();
}
}
85
public class TCFExample
{
public void method ()
{
BufferedReader br;
String s;
int num;
try
{
System.out.print("Type in an integer: ");
br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine();
num = Integer.parseInt(s);
return;
}

86
catch (IOException e)
{
e.printStackTrace();
return;
}
catch (NumberFormatException e)
{
e.printStackTrace ();
return;
}
finally
{
System.out.println("<<<This code will always execute>>>");
return;
}
}
87 }
• 2 cách làm việc với ngoại lệ
§ Xử lý ngay: Dùng khối try..catch ..finally
• Ủy nhiệm cho ví trí nó gọi
§ Xử lý ngay hoặc
§ throw ra ngòai phạm vi
o Xử dung từ khóa throw

88
• Phương thức ủy nhiệm vị trí nó gọi bằng
cách:
• Sử dung throws ở phần định nghĩa phương
thức để báo hiệu cho vị trí ExceptionType gọi
nó biết nó có thể phát sinh ngoại lệ
ExceptionType
• Sử dung throw anExceptionObject trong thân
phương thức để tung ra ngoại lệ khi cần

89
public void myMethod(int param) throws Exception
{
if (param < 10)
{
throw new Exception("Too low!");
}
//...
}

90
• Nếu phương thức có chứa câu lệnh tung ngoại lệ
(throw) thì phần khai báo phương thức phải khai báo là
có tung ngoại lệ đó hoặc lớp cha của ngoại lệ đó
public void myMethod(int param) {
if (param < 10) {
throw new Exception("Too low!");
}
Ø unreported exception java.lang.Exception; must be
caught or declared to be thrown

91
• Phương thức không cần phải khai báo sẽ tung ra
RuntimeException vì ngoại lệ này mặc định được ủy
nhiệm cho JVM
• Ví dụ:
class Test {
public void myMethod(int param)
{
if (param < 10) {
throw new RuntimeException("Too low!");
}
// ...
}
} //OK
92
• Tại vị trí gọi phương thức có ủy nhiệm ngoại lệ (trừ
RuntimeException):
§ Hoặc là phương thức chứa vị trí đó phải ủy nhiệm
tiếp cho vị trí gọi mình
§ Hoặc là tại ví trí gọi phải bắt ngoại lệ ủy nhiệm (hoặc
lớp cha) và xử lý ngay bằng try...catch (finally nếu
cần)

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

94
public static void main(String[] args) {
try {
int num = calculate(9,3);
System.out.println("Lan 1: " + num);
num = calculate(9,0);
System.out.println("Lan 2: " + num);
} catch(Exception e) {
System.out.println(e.getMessage());
}

95
• Một phương thức có thể ủy nhiệm nhiều
hơn 1 ngoại lệ:
public void myMethod(int tuoi, String ten)
throws ArithmeticException, NullPointerException
{
if (tuoi < 18) {
throw new ArithmeticException(“Chua du tuoi!");
}
if (ten == null)
{
throw new NullPointerException(“Thieu ten!");
}
}

96
• Tình huống:
§ Giả sử trong main() gọi phương thức A(),
trong A() gọi B(), trong B() gọi C().
§ Khi đó một ngăn xếp các phương thức được
tạo ra.
§ Giả sử trong C() xảy ra ngoại lệ

97
• Nếu C() gặp lỗi và tung ra ngoại lệ nhưng trong C() lại
không xử lý ngoại lệ này, thì 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().
• Nếu trong B() cũng không xử lý thì phải xử lý ngoại lệ
này trong A()... Quá trình này gọi là lan truyền ngoại lệ
• Nếu đến main() cũng không xử lý ngoại lệ được tung từ
C() thì chương trình sẽ phải dừng lại.

98
• 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
ØPhương thức ghi đè trong lớp con chỉ
được phép tung ra các ngoại lệ giống
hoặc là lớp con của các ngoại lệ được
tung ra ở lớp cha.

99
class Disk {
void readFile() throws EOFException {}
}
class FloppyDisk extends Disk {
void readFile() throws IOException {} // ERROR!
}

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

100
IOException

These classes are


instances of class
IOException

EOFException FileNotFound
Exception

101
• Khi xử lý một chuỗi các biệt lệ cần phải
đảm bảo rằng các biệt lệ lớp con được xử
lý trước các biệt lệ của lớp cha.
• Xử lý các trường hợp cụ thể trước khi xử
lý các trường hợp tổng quát

102
Đúng Sai
try try
{ {

} }
catch (EOFException e) catch (IOException e)
{ {

} }
catch (IOException e) catch (EOFException e)
{ {

} }

103
• Dễ sử dụng
– Làm chương trình dễ đọc và an toàn hơn
– Dễ dàng chuyển điều khiển đến nơi có khả năng xử
lý ngoại lệ
– Có thể ném nhiều loại ngoại lệ
• Tách xử lý ngoại lệ khỏi đoạn mã thông thường
• Không bỏ sót ngoại lệ (ném tự động)
• Gom nhóm và phân loại các ngoại lệ
• Làm chương trình dễ đọc và an toàn hơn

104
• IOException
• NumberFormatException
• NullPointerException
• ArrayIndexOutOfBoundException
• StringIndexOutOfBound
• ArithmeticException
• FileNotFoundException
• SQLException
105
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));

while ((sCurrentLine = br.readLine()) != null) {


System.out.println(sCurrentLine);
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
106
public static void main(String args[])
{
try{
int num=Integer.parseInt ("XYZ") ;
System.out.println(num);
}catch(NumberFormatException e)
{
System.out.println("Number format exception
occurred");
}
}

107
• Ngoại lệ xãy ra khi truy xuất đến các phần thành phần
của tượng chưa được khởi tạo
• Ví dụ: int [] arr=null;
try{
arr[0] = 1;
}catch(NullPointerException e)
{
System.out.print("Mảng bị null\n");
e.printStackTrace();
}
System.out.print("do thing");

108
• Xãy ra khi truy xuất các phần tử có chỉ số không
hợp lệ int[] marks = { 40, 50, 60 };
System.out.println("Hello 1");
• Ví dụ:
try
{
int m1 = marks[3];
System.out.println("Marks are " + m1);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Do not cross size of array sir." + e );
}
System.out.println("Hello 2");
System.out.println("Hello 3");

109
public static void main(String args[])
{
try{
String str="beginnersbook";
System.out.println(str.length());
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndex Exception!!");
}
}

110
• Xảy ra khi phép tính số học không hợp lệ
• Ví dụ:
try{
int tu=1, mau=0;
int phanso=tu/mau;
System.out.println (”Kết quả: "+phanso);
} catch(ArithmeticException e)
{
System.out.println (”mẫu số bằng 0");
}

111
public sta*c void main(String args[])
{
FileInputStream fis = null;
try
{
fis = new FileInputStream("abc.txt");
}
catch(FileNotFoundExcep*on e)
{
System.out.println("The source file does not exist. " + e);
}

112
• Phát sinh khi thao tác trên CSDL
• Ví dụ:
Connection conn = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
Statement stmt = conn.createStatement();
String sql; sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

113
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last"); //Display values
System.out.print("ID: " + id); System.out.print(", Age: " + age);
System.out.print(", First: " + first); System.out.println(", Last: " + last);
}
}catch(SQLException se){
se.printStackTrace();
}

114
try
{

NO!
s = stringInput.readLine();
num = Integer.parseInt (s);
}
catch (IOException e)
{
System.out.println(e);
}
catch (NumberFormatException e)
{
// Do nothing here but set up the try-catch block to bypass
the
// annoying compiler error
}

115
Throwable

Error Exception

VirtualMachineError
… IOException ??? RunTime
… Exception

OutOfMemoryError

116 Excerpt from Big Java by C. Horstmann p. 562


Exception

ClassNotFound IOException CloneNotFound


Exception Exception

EOFException FileNotFound MalformedURL UnknownHost


Exception Exception Exception

117
• Các ngoại lệ do hệ thống xây dựng không đủ để kiểm
soát tất cả các lỗi Cần phải có các lớp ngoại lệ do
người dùng định nghĩa.
§ Kế thừa từ một lớp Exception hoặc lớp con của nó
§ Có tất cả các phương thức của lớp Throwable
public class MyException extends Exception {
public MyException(String msg) {
super(msg);
}

public MyException(String msg, Throwable cause){


super(msg, cause);
}
}

118
public class FileExample {
public void copyFile(String fName1,String
fName2) throws MyException {
if (fName1.equals(fName2))
throw new MyException("File trung ten");

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

119
public class Test {
public static void main(String[] args) {
FileExample obj = new FileExample();
try {
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());
}

120
Ngoại&lệ Lớp&cha&của&thứ&tự&phân&cấp&ngoại&lệ
RuntimeException Lớp&cơ&sở&cho&nhiều&ngoại&lệ&java.lang
ArthmeticException Lỗi&về&số&học,&ví&dụ&như&‘chia&cho&0’.
IllegalAccessException Lớp&không&thể&truy&cập.
IllegalArgumentException Đối&số&không&hợp&lệ.
ArrayIndexOutOfBoundsExeptionLỗi&tràn&mảng.
NullPointerException Khi&truy&cập&đối&tượng&null.
SecurityException Cơ&chế&bảo&mật&không&cho&phép&thực&hiện.
ClassNotFoundException Không&thể&nạp&lớp&yêu&cầu.
Việc& chuyển& đối& từ& chuỗi& sang& số& thực& không&
NumberFormatException thành&công.
AWTException Ngoại&lệ&về&AWT
IOException Lớp&cha&của&các&lớp&ngoại&lệ&I/O
FileNotFoundException Không&thể&định&vị&tập&tin
EOFException Kết&thúc&một&tập&tin.
NoSuchMethodException Phương&thức&yêu&cầu&không&tồn&tại.
InterruptedException Khi&một&luồng&bị&ngắt.
121
!

You might also like