SlideShare a Scribd company logo
1 of 30
Download to read offline
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ắt
luồ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ác
của chương trình
• Một chương trình có thể chia thành luồng
thực hiện bình thường và luồng thực hiện
biệ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ệ
Errors
Object
Throwable
Error Exception
VirtualMachine
Error
Linkage
Error
…
Internal
Error
OutOfMemory
Error
StackOverflow
Error
Unknown
Error
Exceptions
Object
Throwable
Error Exception
FileNotFound
Exception
EOF
Exception
ClassNotFound
Exception
CloneNotSupported
Exception
IO
Exception
Arithmetic
Exception
RunTIme
Exception
NullPointer
Exception
IndexOutOfBounds
Exception
… …
…
Biệt lệ kiểm duyệt và không kiểm
duyệt
• Biệt lệ chia làm 2 nhóm : được kiểm duyệt
và 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 IgnoreEx
The start of IgnoreEx
Exception in thread "main" java.lang.ArithmeticException: /
by zero
at IgnoreEx.main(IgnoreEx.java:8)
Propogating an Exception
• Trong trường hợp một biệt lệ kiểm duyệt
khô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 Example
public 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ơi
biệ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ảy
ra, có thể xử lý tại mức cao hơn trong
chương trình
• Biệt lệ có thể truyền lên trên qua gọi
phươ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 PropagationTester
Start of Program
Start of level1
Start of level2
Start of level3
Message is: / by zero
StackTrace 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 ThrowDemo
Exception 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 AnotherExample
Enter your age: 32
Your current age is 32
>java AnotherExample
Enter your age: 1234
Are you sure you are that old?
>java AnotherExample
Enter your age: -2
That's impossible!!
Ví dụ
>java AnotherExample
Enter your age: asd
Exception 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)

More Related Content

What's hot

Lập Trình an toàn - Secure programming
Lập Trình an toàn - Secure programmingLập Trình an toàn - Secure programming
Lập Trình an toàn - Secure programmingbeatmaking
 
Lap trinh java hieu qua
Lap trinh java hieu quaLap trinh java hieu qua
Lap trinh java hieu quaLê Anh
 
Oop unit 05 một số kỹ thuật java nâng cao
Oop unit 05 một số kỹ thuật java nâng caoOop unit 05 một số kỹ thuật java nâng cao
Oop unit 05 một số kỹ thuật java nâng caoTráng Hà Viết
 
Core java 7
Core java 7Core java 7
Core java 7. .
 
Oop unit 04 các kỹ thuật xây dựng lớp
Oop unit 04 các kỹ thuật xây dựng lớpOop unit 04 các kỹ thuật xây dựng lớp
Oop unit 04 các kỹ thuật xây dựng lớpTráng Hà Viết
 

What's hot (8)

Lập Trình an toàn - Secure programming
Lập Trình an toàn - Secure programmingLập Trình an toàn - Secure programming
Lập Trình an toàn - Secure programming
 
Linq net
Linq net Linq net
Linq net
 
Lap trinh java hieu qua
Lap trinh java hieu quaLap trinh java hieu qua
Lap trinh java hieu qua
 
Oop unit 05 một số kỹ thuật java nâng cao
Oop unit 05 một số kỹ thuật java nâng caoOop unit 05 một số kỹ thuật java nâng cao
Oop unit 05 một số kỹ thuật java nâng cao
 
Core java 7
Core java 7Core java 7
Core java 7
 
Bai08 lap trinhtongquat
Bai08 lap trinhtongquatBai08 lap trinhtongquat
Bai08 lap trinhtongquat
 
Oop unit 04 các kỹ thuật xây dựng lớp
Oop unit 04 các kỹ thuật xây dựng lớpOop unit 04 các kỹ thuật xây dựng lớp
Oop unit 04 các kỹ thuật xây dựng lớp
 
CHUONG_5
CHUONG_5CHUONG_5
CHUONG_5
 

Chuong4 exception

  • 2. 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ắt luồ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; }
  • 3. 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ác của chương trình • Một chương trình có thể chia thành luồng thực hiện bình thường và luồng thực hiện biệ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ệ
  • 6. Biệt lệ kiểm duyệt và không kiểm duyệt • Biệt lệ chia làm 2 nhóm : được kiểm duyệt và 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
  • 7. 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)
  • 8. 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”); } }
  • 9. Ví dụ • Đầu ra sẽ là % java IgnoreEx The start of IgnoreEx Exception in thread "main" java.lang.ArithmeticException: / by zero at IgnoreEx.main(IgnoreEx.java:8)
  • 10. Propogating an Exception • Trong trường hợp một biệt lệ kiểm duyệt khô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;
  • 11. Propagation Example public static void main(String[] args) throws IOException, FileNotFoundException { ... }
  • 12. Xử lý biệt lệ • Sử dụng khối lệnh try…catch…finally tại nơi biệt lệ xảy ra • Cú pháp được thực hiện như sau : try { … } catch(Exception e) { … } … finally { … }
  • 13. 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 }
  • 14. Truyền biệt lệ • Nếu biệt lệ không được xử lý tại vị trí xảy ra, có thể xử lý tại mức cao hơn trong chương trình • Biệt lệ có thể truyền lên trên qua gọi phươ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)
  • 15. 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"); } }
  • 16. 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"); }
  • 17. 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(); } }
  • 18. Đầu ra >java PropagationTester Start of Program Start of level1 Start of level2 Start of level3 Message is: / by zero StackTrace 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
  • 19. 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
  • 20. 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; } }
  • 21. Ví dụ import java.io.IOException; public class Oops extends IOException { Oops(String message) { super(message); } }
  • 22. Ví dụ > java ThrowDemo Exception in thread "main" Oops: That wasn't supposed to happen! at ThrowDemo.main(ThrowDemo.java:19)
  • 23. 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ệ
  • 24. Ví dụ public class AnotherExample { public static void main(String[] args) { AnotherExample x = new AnotherExample(); x.run(); }
  • 25. 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!!"); } }
  • 26. 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; } } }
  • 27. Ví dụ public class NumberTooBigException extends Exception { public NumberTooBigException() { super(); } public NumberTooBigException(String message) { super(message); } }
  • 28. Ví dụ public class NumberTooSmallException extends Exception { public NumberTooSmallException() { super(); } public NumberTooSmallException(String message) { super(message); } }
  • 29. Ví dụ >java AnotherExample Enter your age: 32 Your current age is 32 >java AnotherExample Enter your age: 1234 Are you sure you are that old? >java AnotherExample Enter your age: -2 That's impossible!!
  • 30. Ví dụ >java AnotherExample Enter your age: asd Exception 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)