chuong4 exception
DESCRIPTION
TRANSCRIPT
Biệt lệ trong Java
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; }
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ệ
ErrorsObject
Throwable
Error Exception
VirtualMachineError
LinkageError
…
InternalError
OutOfMemoryError
StackOverflowError
UnknownError
ExceptionsObject
Throwable
Error Exception
FileNotFoundException
EOFException
ClassNotFoundException
CloneNotSupportedException
IOException
ArithmeticException
RunTImeException
NullPointerException
IndexOutOfBoundsException
… …
…
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
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)
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”);
}}
Ví dụ
• Đầu ra sẽ là
% java IgnoreExThe start of IgnoreExException in thread "main" java.lang.ArithmeticException: /
by zeroat IgnoreEx.main(IgnoreEx.java:8)
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;
Propagation Examplepublic static void main(String[] args)
throws IOException, FileNotFoundException{
...}
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{ …}
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}
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)
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");
}}
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");
}
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();
}}
Đầ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
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
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;
}}
Ví dụimport java.io.IOException;
public class Oops extends IOException{
Oops(String message){
super(message);}
}
Ví dụ> java ThrowDemoException in thread "main" Oops: That wasn't supposed to happen!
at ThrowDemo.main(ThrowDemo.java:19)
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ệ
Ví dụpublic class AnotherExample{
public static void main(String[] args){
AnotherExample x = new AnotherExample();x.run();
}
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!!");}
}
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;}
}}
Ví dụpublic class NumberTooBigException extends Exception{
public NumberTooBigException(){
super();}public NumberTooBigException(String message){
super(message);}
}
Ví dụpublic class NumberTooSmallException extends Exception{
public NumberTooSmallException(){
super();}public NumberTooSmallException(String message){
super(message);}
}
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!!
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)