Upload
thanh-vu
View
215
Download
0
Embed Size (px)
Citation preview
8/12/2019 Chuong 10 Xu Ly Ngoai Le
1/8
8/24/2011
1
LP TRNH JAVA
Chng 10. X l ngoi l
Trnh Tun tEmail: [email protected]
B mn Cng ngh Phn mmVin CNTT & TT
Trng i hc Bch Khoa H Ni
Ni dung
1.
Ngoi l2. Bt v x l ngoi l
3. y nhim ngoi l
4. To ngoi l tnh ngha
Ni dung
1. Ngoi l
2. Bt v x l ngoi l
3. y nhim ngoi l
4. To ngoi l tnh ngha
a. Ngoi l l g?
Nguyn nhn: iu kin ch quan
iu kin khch quan
a. Ngoi l l g? (2)
Exception = Exceptional event nh ngha:
V d:
a. Ngoi l l g? (3)
mailto:[email protected]:[email protected]8/12/2019 Chuong 10 Xu Ly Ngoai Le
2/8
8/24/2011
2
7
b. Cch x l li truyn thng
Vit m x l ti ni pht sinh ra li
Truyn trng thi ln mc trn
8
int devide(int num, int denom, int *error)
{if (denom != 0){
error = 0;
return num/denom;
} else {
error = 1;
return 0;
}
}
V d
Nhc im Ni dung
1. Ngoi l
2. Bt v x l ngoi l
3. y nhim ngoi l
4. To ngoi l tnh ngha
2. X l ngoi l trong Java(Exception Handling)
Khi x l li
IF B IS ZERO GO TO ERRORC = A/BPRINT CGO TO EXIT
ERROR:DISPLAY DIVISION BY ZERO
EXIT:END
1212
a. Khi trycatch
try {
// Doan ma co the gay ngoai le
}
catch (ExceptionType e) {
// Xu ly ngoai le
}
8/12/2019 Chuong 10 Xu Ly Ngoai Le
3/8
8/24/2011
3
V d khng x l ngoi l
class NoException {
public static void main(String args[]) {
String text = args[0];
System.out.println(text);
}
}
V d c x l ngoi l
class ArgExceptionDemo {
public static void main(String args[]) {try {
String text = args[0];
System.out.println(text);
}
catch(Exception e) {
System.out.println(Hay nhap tham so khi chay!");
}
}
}
X l ngoi l trong Java
X l ngoi l trong Javac thc hin theo m hnhhng i tng:
V d
public class ChiaCho0Demo {
public static void main(String args[]){
try {
int num = calculate(9,0);
System.out.println(num);
}
catch(Exception e) {
System.err.println("Co loi xay ra: " + e.toString());
}
}
static int calculate(int no, int no1){
int num = no / no1;
return num;
}
}
b. Cu trc phn cp ngoi l
Object
Throwable
Error Exception
RuntimeException
...
......
18
b. Cu trc phn cp ngoi l (2)
Lp Throwable
Mt s phng thc c bn new Throwable(String s);
String getMessage();
void printStackTrace();
8/12/2019 Chuong 10 Xu Ly Ngoai Le
4/8
8/24/2011
4
public class StckExceptionDemo {
public static void main(String args[]){
try {
int num = calculate(9,0);
System.out.println(num);
}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;
}
}
20
b. Cu trc phn cp ngoi l (3)
Lp Exception
Lp Error
21
b. Cu trc phn cp ngoi l (4)
RuntimeException:
NullPointException: con tr null
OutOfMemoryException: ht b nh
ArithmeticException: li ton hc, li chia khng
ClassCastException: li p kiu
ArrayIndexOutOfBoundsException: vt qu ch s mng
...
c. Khi try catch lng nhau
try {
// Doan ma co the gay ra IOException
try {
// Doan ma co the gay ra NumberFormatException} catch (NumberFormatException e1) {
// Xu ly loi sai dinh dang so
}
} catch (IOException e2) {
// Xu ly loi vao ra
}
d. Nhiu khi catch
S dng nhiu khi catch.try {
// Doan ma co the gay ra nhieu ngoai le
} catch (ExceptionType1 e1) {
// Xu ly ngoai le 1} catch (ExceptionType2 e2) {
// Xu ly ngoai le 2
} ...
class MultipleCatch {
public static void main(String args[])
{
try {
String num = args[0];
int numValue = Integer.parseInt(num);
System.out.println("Dien tich hv la: "
+ numValue * numValue);
} catch(Exception e1) {
System.out.println(Hay nhap canh cua hv!");} catch(NumberFormatException e2){
System.out.println("Not a number!");
}
}
}
Li
8/12/2019 Chuong 10 Xu Ly Ngoai Le
5/8
8/24/2011
5
class MultipleCatch {
public static void main(String args[]){
try {
String num = args[0];
int numValue = Integer.parseInt(num);
System.out.println("Dien tich hv la: "
+ numValue * numValue);
} catch(ArrayIndexOutOfBoundsException e1) {
System.out.println(Hay nhap canh cua hv!");
} catch(NumberFormatException e2){
System.out.println(Hay nhap 1 so!");
}
}
}
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) {
//do something clever with the exception
} catch (IOException e) {
//do something clever with the exception
}
}
e. Khi finally
m bo thc hin tt c cc cng vic cn thitkhi c ngoi l xy ra
catch block finallyException
finallyNo exception
try block
C php try ... catch ... finally
try {
// Khoi lenh co the sinh ngoai le
}
catch(TypeOfException e) {
// Bat va xu ly ngoai le
}
finally {
/* Thuc hien cac cong viec can thiet du ngoai le coxay ra hay khong */
}
class StrExceptionDemo {
static String str;
public static void main(String str[]) {
try {
System.out.println(Truoc ngoai le");
staticLengthmethod();
System.out.println(Sau ngoai le"); //khong thuc hien
}
catch(NullPointerException ne) {
System.out.println(Da xay ra loi");
}
finally {
System.out.println(Trong finally");
}
}
static void staticLengthmethod() {
System.out.println(str.length());
}
}
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 );
}
} 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 ---");
}
}
8/12/2019 Chuong 10 Xu Ly Ngoai Le
6/8
8/24/2011
6
Ni dung
1.
Ngoi l2. Bt v x l ngoi l
3. y nhim ngoi l
4. To ngoi l tnh ngha
Hai cch lm vic vi ngoi l trong Java
X l ngay
y nhim:
3. y nhim (tung) ngoi l
Phng thc c th y nhim (tung ra) ngoi lcho v tr gi n bng cch: S dng throws ExceptionType
S dng throw anExceptionObject
public void myMethod(int param) throws Exception {
if (param < 10) {
throw new Exception("Too low!");}
//Blah, Blah, Blah...
}
3. y nhim ngoi l (2)
public void myMethod(int param) {
if (param < 10) {
throw new Exception("Too low!");}
//Blah, Blah, Blah...
}
unreported exception java.lang.Exception; must becaught or declared to be thrown
Ti v tr gi phng thc c y nhimngoi l hoc:
3. y nhim ngoi l (3)public class DelegateExceptionDemo {
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());
}
}
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;
}
}
8/12/2019 Chuong 10 Xu Ly Ngoai Le
7/8
8/24/2011
7
3. y nhim ngoi l (4)
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!");
}
//Blah, Blah, Blah...
}
38
Lan truyn ngoi l
Tnh hung:
39
Lan truyn ngoi l
C()
B()
A()
main()
B()
A()
main()
C() tung ngo
3. y nhim ngoi l (5)
Phng thc ghi trong lp con ch c phptung ra cc ngoi l ging hoc l lp con ca ccngoi l c tung ra lp cha.
3. y nhim ngoi l (6)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
}
Ni dung
1. Ngoi l
2. Bt v x l ngoi l
3. y nhim ngoi l
4. To ngoi l tnh ngha
8/12/2019 Chuong 10 Xu Ly Ngoai Le
8/8
8/24/2011
8
Ngoi l ngi dng nh ngha
Cc ngoi l do h thng xy dng khng kim sot tt c cc li
public class MyException extends Exception {
public MyException(String msg) {
super(msg);
}
}
44
public class Example{
public void copy(String fileName1, String fileName2)
throwsMyException
{
if (fileName1.equals(fileName2))
throw newMyException("File trung ten");
// Copy file
System.out.println("Copy completed");
}
}
S dng ngoi l ngi dng nh ngha
45
S dng ngoi l ngi dng nh ngha
Bt v x l ngoi l
public class Test {public static void main(String[] args) {
Example obj = new Example();try {String a = args[0];String b = args[1];obj.copy(a,b);} catch (MyException e1) {
System.out.println(e1.getMessage());}catch(Exception e2) {
System.out.println(e2.toString());}
}}
4646
uimcanmbtngoil
D s dng