Bài giảng Lập trình hướng đối tượng - Bài 08: Ngoại lệ và xử lý ngoại lệ
8/24/2011
Mục tiêu của bài học
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
Giải thích được mô hình xử lý ngoại lệ
Sử dụng khối try/catch/finally để bắt và xử lý
ngoại lệ trong Java
Hiểu và biết cách sử dụng ủy nhiệm ngoại lệ
LẬP TRÌNH HƯỚNG ĐỐI TƯỢNG
Bài 08. Ngoại lệ và xử lý ngoại lệ
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ệ
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
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)
Exception = Exceptional event
ERROR !!
Ví dụ:
5
6
1
8/24/2011
Ví dụ
1.2. Cách xử lý lỗi truyền thống
int devide(int num, int denom, int *error)
Viết mã xử lý tại nơi phát sinh ra lỗi
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)
Khi xảy ra ngoại lệ, nếu không có cơ chế xử
lý thích hợp?
11
12
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)
Hướng đối tượng
2 cách
13
17
14
16
18
2.3. Xử lý ngoại lệ trong Java
2.3. Xử lý ngoại lệ trong Java (2)
Java có cơ chế xử lý ngoại lệ rất
mạnh
Các từ khóa
try
catch
finally
throw
throws
Ví dụ không xử lý ngoại lệ
2.3.1. Khối try/catch
class NoException {
Khối try ... catch:
try {
public static void main(String args[]) {
String text = args[0];
// Doan ma co the gay ngoai le
System.out.println(text);
}
}
}
catch (ExceptionType e) {
// Xu ly ngoai le
}
3
8/24/2011
Ví dụ có xử lý ngoại lệ
Ví dụ chia cho 0
public class ChiaCho0Demo
public static void main(String args[]){
try
int num
System.out.println(num);
{
class ArgExceptionDemo
public static void main(String args[])
{
{
{
=
calculate(9,0);
try
}
{
String text
System.out.println(text);
= args[0];
}
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;
}
=
/
}
}
}
19
20
22
24
a. Lớp Throwable
2.3.2. Cây phân cấp ngoại lệ trong Java
Một số phương thức cơ bản?
21
public class StckExceptionDemo
public static void main(String args[]){
try
{
b. Lớp Error
{
int num
= calculate(9,0);
Các lớp con:
System.out.println(num);
}
VirtualMachineError: InternalError,
OutOfMemoryError, StackOverflowError,
UnknownError
ThreadDeath
LinkageError:
catch(Exception e)
System.err.println(“Co loi xay ra :"
e.getMessage());
{
+
e.printStackTrace();
}
}
static int calculate(int no, int no1)
int num no no1;
return num;
{
IncompatibleClassChangeError
=
/
AbstractMethodError, InstantiationError, NoSuchFieldError,
NoSuchMethodError…
}
}
…
…
23
4
8/24/2011
c. Lớp Exception
Một số lớp con của Exception
ClassNotFoundException, SQLException
java.io.IOException:
Chứa các loại ngoại lệ
nên/phải bắt và xử lý
hoặc ủy nhiệm.
FileNotFoundException, EOFException…
RuntimeException:
NullPointerException, BufferOverflowException
ClassCastException, ArithmeticException
IndexOutOfBoundsException:
RuntimeException?
ArrayIndexOutOfBoundsException,
StringIndexOutOfBoundsException…
IllegalArgumentException:
NumberFormatException, InvalidParameterException…
…
25
27
29
26
Ví dụ IOException
import java.io.InputStreamReader;
2.3.3. Khối try – catch lồng nhau
import java.io.IOException;
try
{
public class HelloWorld{
// Doan ma co the gay ra IOException
public static void main(String[] args)
{
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
System.out.print("Nhap vao
char (char) isr.read();
System.out.println("Ky tu vua nhap:
}catch(IOException ioe)
{
1
ky tu: ");
}
}
catch (IOException e2)
// Xu ly loi vao ra
{
c
=
"
+ c);
{
ioe.printStackTrace();
}
}
28
}
2.3.4. Nhiều khối catch
vEớxiceEpxtcieopntTioynpTe1yppeh2ả(itlràonlớgpccâoynphhoâặnccnấgpaknếg thhàừnag)
class MultipleCatch1
{
try {
public static void main(String args[])
// Doan ma co the gay ra nhieu ngoai
le
{
try
String num
int numValue
System.out.println("Dien tich hv la:
numValue numValue);
{
=
args[0];
Integer.parseInt(num);
} catch (ExceptionType1 e1) {
// Xu ly ngoai le 1
} catch (ExceptionType2 e2) {
// Xu ly ngoai le 2
} ...
=
"
+
*
}
}
catch(Exception e1) {
System.out.println("Hay nhap canh cua hv!");
catch(NumberFormatException e2){
System.out.println("Not
a number!");
}
}
}
30
5
8/24/2011
class MultiCatch2
public static void main( String args[])
try
// format
// read
// something else...
{
class MultipleCatch1
public static void main(String args[])
{
{
{
{
try
String num
int numValue
System.out.println("Dien tich hv la:
numValue numValue);
catch(ArrayIndexOutOfBoundsException e1)
{
a
number
=
args[0];
Integer.parseInt(num);
a
file
=
"
}
+
*
catch(IOException e)
{
}
}
{
System.out.println("I/O error "+e.getMessage();
System.out.println(“Hay nhap canh cua hv!");
catch(NumberFormatException e2){
}
System.out.println(“Hay nhap
1 so!");
catch(NumberFormatException e)
{
}
System.out.println("Bad data "+e.getMessage();
}
}
}
catch(Throwable e)
{ // catch all
System.out.println("error: "
+ e.getMessage();}
}
}
31
33
35
32
}
...
public void openFile(){
try
2.3.5. Khối finally
{
// constructor may throw FileNotFoundException
FileReader reader
int i=0;
= new FileReader("someFile");
while(i != -1)
//reader.read() may throw IOException
;
System.out.println((char)
{
i
);
}
reader.close();
System.out.println("--- File End ---");
}
}
}
catch (FileNotFoundException e)
//do something clever with the exception
{
No exception
finally
catch (IOException e)
{
//do something clever with the exception
try block
catch block
finally
}
...
Exception
34
class StrExceptionDemo
static String str;
public static void main(String s[])
try
{
Cú pháp try ... catch ... finally
{
{
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
{
/* Thuc hien cac cong viec can thiet du
ngoai le co xay ra hay khong */
System.out.println(“Trong finally");
}
}
}
static void staticLengthmethod()
{
System.out.println(str.length());
}
}
36
6
8/24/2011
public void openFile(){
try
// constructor may throw FileNotFoundException
Nội dung
{
FileReader reader
int i=0;
= new FileReader("someFile");
1. Ngoại lệ
while(i != -1)
//reader.read() may throw IOException
reader.read();
System.out.println((char)
{
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
i
=
i
);
}
}
}
}
catch (FileNotFoundException e)
//do something clever with the exception
catch (IOException e)
//do something clever with the exception
{
{
finally
{
reader.close();
System.out.println("--- File End ---");
}
}
37
39
41
38
3.1. Ủy nhiệm ngoại lệ
Hai cách làm việc với ngoại lệ
Xử lý ngay
Ủy nhiệm cho vị trí gọi nó:
Ví dụ
public void myMethod(int param) throws
Exception{
if (param < 10) {
throw new Exception("Too low!");
}
//Blah, Blah, Blah...
}
40
3.1. Ủy nhiệm ngoại lệ (3)
public class DelegateExceptionDemo
public static void main(String args[]){
int num calculate(9,3);
System.out.println(“Lan 1:
num calculate(9,0);
System.out.println(“Lan 2:
{
=
”
”
+
+
num);
num);
Ví dụ
class Test {
=
public void myMethod(int param) {
if (param < 10) {
throw new RuntimeException("Too
low!");
}
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;
//Blah, Blah, Blah...
=
/
}
}
}
}
Không lỗi?
42
7
8/24/2011
public class DelegateExceptionDemo
public static void main(String args[]){
int num calculate(9,3);
System.out.println(“Lan 1:
num calculate(9,0);
System.out.println(“Lan 2:
{
public class DelegateExceptionDemo
public static void main(String args[]){
try
{
=
”
”
+
+
num);
num);
{
=
int num
System.out.println(“Lan 1:
num calculate(9,0);
System.out.println(“Lan 2:
catch(Exception e)
System.out.println(e.getMessage());
= calculate(9,3);
”
”
+
+
num);
num);
}
=
static int calculate(int no, int no1)
throws Exception
{
}
}
{
if (no1 == 0)
throw new
ArithmeticException("Khong the chia cho 0!");
int num no no1;
return 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;
=
/
}
43
44
}
3.1. Ủy nhiệm ngoại lệ (4)
3.2. Lan truyền ngoại lệ
C() tung ngoại lệ
Ủy nhiệm nhiều hơn 1 ngoại lệ
C()
public void myMethod(int tuoi, String ten)
throws ArithmeticException, NullPointerException{
B()
A()
B()
A()
if (tuoi
< 18) {
main()
throw new ArithmeticException(“Chua du tuoi!");
main()
}
if (ten == null)
{
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().
throw new NullPointerException(“Thieu ten!");
}
//Blah, Blah, Blah...
}
…
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
{
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
void readFile() throws EOFException {}
}
class FloppyDisk extends Disk
{
void readFile() throws IOException {}
}
class Disk
{
void readFile() throws IOException {}
}
class FloppyDisk extends Disk
{
void readFile() throws EOFException {}
}
47
48
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
51
53
50
49
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 class FileExample
public MyException(String msg)
{
{
super(msg);
}
public void copyFile(String fName1,String fName2)
throws MyException
public MyException(String msg, Throwable cause){
{
if (fName1.equals(fName2))
throw new MyException("File trung ten");
// Copy file
super(msg, cause);
}
}
System.out.println("Copy completed");
}
}
52
Sử dụng ngoại lệ người dùng định nghĩa
Bắt và xử lý ngoại lệ
public class Test
public static void main(String[] args)
FileExample obj new FileExample();
{
{
=
try
{
String
String
a
b
=
=
args[0];
args[1];
obj.copyFile(a,b);
catch (MyException e1)
System.out.println(e1.getMessage());
}
}
{
catch(Exception e2)
{
System.out.println(e2.toString());
}
}
}
9
Bạn đang xem tài liệu "Bài giảng Lập trình hướng đối tượng - Bài 08: Ngoại lệ và xử lý ngoại lệ", để tải tài liệu gốc về máy hãy click vào nút Download ở trên
File đính kèm:
- bai_giang_lap_trinh_huong_doi_tuong_bai_08_ngoai_le_va_xu_ly.pdf