chuong4 exception

30
Biệt lệ trong Java

Upload: nguyen-tat

Post on 29-Nov-2014

307 views

Category:

Documents


2 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Chuong4 exception

Biệt lệ trong Java

Page 2: Chuong4 exception

Biệt lệ là gì? • Một biệt lệ là một đối tượng mô tả một trạng thái

không mong muốn xảy ra trong chương trình• Định nghĩa: Một biệt lệ là một sự kiện xảy ra

trong quá trình thực hiện chương trình ngắtluồng công việc thực hiện bình thường

int a = 4, b = 4;int[] intAy = new int[4];intAy[0] = a / (a - b); for (int k = 1; k <= 4; ++k){

intAy[k] = a * k; }

Page 3: Chuong4 exception

Biệt lệ

• Biệt lệ được sinh ra bởi chương trình cóthể được bắt và xử lý bởi một đoạn kháccủa chương trình

• Một chương trình có thể chia thành luồngthực hiện bình thường và luồng thực hiệnbiệt lệ

• Nhiều biệt lệ được định nghĩa tại java.lang• java.lang.Throwable là lớp đỉnh của các

lớp lỗi và biệt lệ

Page 4: Chuong4 exception

ErrorsObject

Throwable

Error Exception

VirtualMachineError

LinkageError

InternalError

OutOfMemoryError

StackOverflowError

UnknownError

Page 5: Chuong4 exception

ExceptionsObject

Throwable

Error Exception

FileNotFoundException

EOFException

ClassNotFoundException

CloneNotSupportedException

IOException

ArithmeticException

RunTImeException

NullPointerException

IndexOutOfBoundsException

… …

Page 6: Chuong4 exception

Biệt lệ kiểm duyệt và không kiểmduyệt

• Biệt lệ chia làm 2 nhóm : được kiểm duyệtvà không được kiểm duyệt

• Mọi lớp con của RuntimeException mô tảcác biệt lệ không kiểm duyệt (unchecked)

• Mọi biệt lệ khác là kiểm duyệt (checked)• Một biệt lệ kiểm duyệt phải được xử lý

trong chương trình• Việc xử lý biệt lệ không kiểm duyệt là tùy

chọn

Page 7: Chuong4 exception

Xử lý biệt lệ

• Một chương trình có thể xử lý một biệt lệtheo 3 cách :– Bỏ qua (chỉ với các biệt lệ không kiểm duyệt)– Xử lý nó tại nơi nó xảy ra– Xử lý nó tại một điểm khác trong chương trình

(propagate it)

Page 8: Chuong4 exception

Ví dụpublic class IgnoreEx{

public static void main(String[] args) {

int a = 4, b = 4;int intAy;System.out.println(“The start of IgnoreEx”);intAy = a / (a - b); System.out.println(“The end of IgnoreEx”);

}}

Page 9: Chuong4 exception

Ví dụ

• Đầu ra sẽ là

% java IgnoreExThe start of IgnoreExException in thread "main" java.lang.ArithmeticException: /

by zeroat IgnoreEx.main(IgnoreEx.java:8)

Page 10: Chuong4 exception

Propogating an Exception

• Trong trường hợp một biệt lệ kiểm duyệtkhông thể bỏ qua, câu lệnh throw có thểđược dùng để truyền một biệt lệ

• Cú pháp của câu lệnh throw là :

throws exceptionObject;

Page 11: Chuong4 exception

Propagation Examplepublic static void main(String[] args)

throws IOException, FileNotFoundException{

...}

Page 12: Chuong4 exception

Xử lý biệt lệ

• Sử dụng khối lệnh try…catch…finally tại nơibiệt lệ xảy ra

• Cú pháp được thực hiện như sau :

try{ …}catch(Exception e){ …}…finally{ …}

Page 13: Chuong4 exception

Cú pháp của try .... catch

try {

statementTry; // exceptions may be thrown from here}catch(Exception1 e1) {

statementException1; // handle the exception e1}catch(Exception2 e2) {

statementException2; // handle the exception e2}…finally {

statementFinally; // the code will always be executed}

Page 14: Chuong4 exception

Truyền biệt lệ

• Nếu biệt lệ không được xử lý tại vị trí xảyra, có thể xử lý tại mức cao hơn trongchương trình

• Biệt lệ có thể truyền lên trên qua gọiphương thức đến khi được bắt và xử lýhoặc đến khi lên đến mức trên cùng(phương thức main)

Page 15: Chuong4 exception

Ví dụpublic class PropagationTester{

public static void main(String[] args){

System.out.println("Start of Program");DemoClass demo = new DemoClass();demo.level1();System.out.println("End of Program");

}}

Page 16: Chuong4 exception

Ví dụpublic class DemoClass{

public void level3(int value){

System.out.println("Start of level3");int value2 = 1/value;System.out.println("End of level3");

}public void level2(){

System.out.println("Start of level2");level3(0);System.out.println("End of level2");

}

Page 17: Chuong4 exception

Ví dụpublic void level1(){

System.out.println("Start of level1");try{

level2();}catch (ArithmeticException e){

System.out.println("Message is: " + e.getMessage());System.out.println("StackTrace is: ");e.printStackTrace();

}}

Page 18: Chuong4 exception

Đầu ra

>java PropagationTesterStart of ProgramStart of level1Start of level2Start of level3Message is: / by zeroStackTrace is:java.lang.ArithmeticException: / by zero

at DemoClass.level3(DemoClass.java:19)at DemoClass.level2(DemoClass.java:25)at DemoClass.level1(DemoClass.java:33)at PropagationTester.main(PropagationTester.java:20)

End of Program

Page 19: Chuong4 exception

Biệt lệ người dùng tự định nghĩa

• Người lập trình có thể tự định nghĩa lớp biệt lệriêng bằng cách tạo lớp kế thừa mới kế thừa từnhững lớp biệt lệ đã có

• Biệt lệ được xử lý sử dụng lệnh throw• Cú pháp lệnh như sau

throw exceptionObject;• Khi sử dụng throw trong đoạn mã cần tự định

nghĩa lớp biệt lệ• Nếu sử dụng một lớp được định từ trước, khối

catch phải tuân theo quy định

Page 20: Chuong4 exception

Ví dụ

import java.io.IOException;

public class ThrowDemo{

public static void main(String[] args) throws Oops{

Oops problem = new Oops("That wasn't supposed to happen!");throw problem;

}}

Page 21: Chuong4 exception

Ví dụimport java.io.IOException;

public class Oops extends IOException{

Oops(String message){

super(message);}

}

Page 22: Chuong4 exception

Ví dụ> java ThrowDemoException in thread "main" Oops: That wasn't supposed to happen!

at ThrowDemo.main(ThrowDemo.java:19)

Page 23: Chuong4 exception

Câu lệnh throw

• Thường sử dụng throw trong một lệnh if, nếu điều kiện thỏa mãn thì xử lý biệt lệ

Page 24: Chuong4 exception

Ví dụpublic class AnotherExample{

public static void main(String[] args){

AnotherExample x = new AnotherExample();x.run();

}

Page 25: Chuong4 exception

Ví dụpublic void run(){

try{

System.out.println("Your current age is " + getAge());}catch (NumberTooBigException e){

System.out.println(e.getMessage());}catch (NumberTooSmallException e){

System.out.println("That's impossible!!");}

}

Page 26: Chuong4 exception

public int getAge() throws NumberTooBigException, NumberTooSmallException{

Scanner keyboard = new Scanner(System.in);System.out.print("Enter your age: ");int age = keyboard.nextInt();if (age > 130){

throw new NumberTooBigException("Are you sure you are that old?");}else if (age < 0){

throw new NumberTooSmallException();}else{

return age;}

}}

Page 27: Chuong4 exception

Ví dụpublic class NumberTooBigException extends Exception{

public NumberTooBigException(){

super();}public NumberTooBigException(String message){

super(message);}

}

Page 28: Chuong4 exception

Ví dụpublic class NumberTooSmallException extends Exception{

public NumberTooSmallException(){

super();}public NumberTooSmallException(String message){

super(message);}

}

Page 29: Chuong4 exception

Ví dụ>java AnotherExampleEnter your age: 32Your current age is 32

>java AnotherExampleEnter your age: 1234Are you sure you are that old?

>java AnotherExampleEnter your age: -2That's impossible!!

Page 30: Chuong4 exception

Ví dụ>java AnotherExampleEnter your age: asdException in thread "main" java.util.InputMismatchException

at java.util.Scanner.throwFor(Scanner.java:819)at java.util.Scanner.next(Scanner.java:1431)at java.util.Scanner.nextInt(Scanner.java:2040)at java.util.Scanner.nextInt(Scanner.java:2000)at AnotherExample.getAge(AnotherExample.java:42)at AnotherExample.run(AnotherExample.java:26)at AnotherExample.main(AnotherExample.java:20)