LẬP TRÌNH HƯỚNG đối TƯỢNG bài 08 NGOẠI lệ và xử lý NGOẠI lệ

9 352 0
LẬP TRÌNH HƯỚNG đối TƯỢNG   bài 08 NGOẠI lệ và xử lý NGOẠI lệ

Đang tải... (xem toàn văn)

Thông tin tài liệu

8/24/2011 Mục tiêu học Giải thích vềngoại lệlà mô tảcác lợi ích việc xửlý ngoại lệhướng đối tượng Giải thích mô hình xửlý ngoại lệ Sửdụng khối try/catch/finally đểbắt xửlý ngoại lệtrong Java Hiểu biết cách sửdụng ủy nhiệm ngoại lệ Biết cách tạo sửdụng ngoại lệtựđị nh nghĩa 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 k o?sqìmg?g ︰mf?I。h?s ︸mf Bài 08 Ngoại lệvà xửlý ngoại lệ Nội dung Nội dung Ngoại lệ Bắt xửlý ngoại lệ Ủy nhiệm ngoại lệ Tạo ngoại lệtựđị nh nghĩa Ngoạ i lệ Bắt xửlý ngoại lệ Ủy nhiệm ngoại lệ Tạo ngoại lệtựđị nh nghĩa 1.1 Ngoại lệlà gì? 1.1 Ngoại lệlà gì? (2) Exception = Exceptional event dqqnq?@@ Ví dụ: 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ý nơi phát sinh lỗi Truyền trạng thái lên mức { if (denom != 0){ error = 0; return num/denom; } else { error = 1; return 0; } } Nhược điểm Nội dung Ngoại lệ Bắ t xử lý ngoạ i lệ Ủy nhiệm ngoại lệ Tạo ngoại lệtựđị nh nghĩa 10 2.1 Mục đích xửlý ngoại lệ 2.1 Mục đích xửlý ngoại lệ(2) Khi xảy ngoại lệ, chếxử lý thích hợp? ………… IF B IS ZERO GO TO ERROR C = A/B PRINT C GO TO EXIT ERROR: DISPLAY “DIVISION BY ZERO” Khối xử lý lỗi EXIT: END 11 12 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 cách 13 2.3 Xửlý ngoại lệtrong Java 14 2.3 Xửlý ngoại lệtrong Java (2) Các từkhóa Java có chếxửlý ngoại lệrất mạnh try catch finally throw throws 16 15 Ví dụkhông xửlý ngoại lệ 2.3.1 Khối try/catch Khối try catch: class NoException { public static void main(String args[]) { String text = args[0]; System.out.println(text); } } try { // Doan ma co the gay ngoai le } catch (ExceptionType e) { // Xu ly ngoai le } 17 18 8/24/2011 Ví dụcó xửlý ngoại lệ Ví dụchia cho 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 chay!"); } } } 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; } } 19 2.3.2 Cây phân cấp ngoại lệtrong Java 20 a Lớp Throwable Một sốphương thức bản? 21 22 b Lớp Error 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 :" + e.getMessage()); e.printStackTrace(); } } static int calculate(int no, int no1) { int num = no / no1; return num; } } Các lớp con: VirtualMachineError: InternalError, OutOfMemoryError, StackOverflowError, UnknownError ThreadDeath LinkageError: IncompatibleClassChangeError AbstractMethodError, InstantiationError, NoSuchFieldError, NoSuchMethodError… … … 23 24 8/24/2011 c Lớp Exception Một sốlớp Exception ClassNotFoundException, SQLException java.io.IOException: Chứa loại ngoại lệ nên/phải bắt xửlý ủy nhiệm RuntimeException? FileNotFoundException, EOFException… RuntimeException: NullPointerException, BufferOverflowException ClassCastException, ArithmeticException IndexOutOfBoundsException: ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException… IllegalArgumentException: NumberFormatException, InvalidParameterException… … 26 25 Ví dụIOException import java.io.InputStreamReader; import java.io.IOException; public class HelloWorld{ public static void main(String[] args) { InputStreamReader isr = new InputStreamReader(System.in); try { System.out.print("Nhap vao ky tu: "); char c = (char) isr.read(); System.out.println("Ky tu vua nhap: " + c); }catch(IOException ioe) { ioe.printStackTrace(); } } } 2.3.3 Khối try – catch lồng try { // Doan ma co the gay IOException try { // Doan ma co the gay NumberFormatException } catch (NumberFormatException e1) { // Xu ly loi sai dinh dang so } } catch (IOException e2) { // Xu ly loi vao } 28 27 2.3.4 Nhiều khối catch ExceptionType1 phải lớp ngang hàng với ExceptionType2 (trong phân cấp kếthừa) class MultipleCatch1 { 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!"); } } } try { // Doan ma co the gay nhieu ngoai le } catch (ExceptionType1 e1) { // Xu ly ngoai le } catch (ExceptionType2 e2) { // Xu ly ngoai le } 29 30 8/24/2011 class MultipleCatch1 { 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 so!"); } } } 31 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 } } class MultiCatch2 { public static void main( String args[]) { try { // format a number // read a file // something else } catch(IOException e) { System.out.println("I/O error "+e.getMessage(); } catch(NumberFormatException e) { System.out.println("Bad data "+e.getMessage(); } catch(Throwable e) { // catch all System.out.println("error: " + e.getMessage();} } } } 32 2.3.5 Khối finally No exception finally try block catch block Exception 33 Cú pháp try catch finally finally 34 class StrExceptionDemo { static String str; public static void main(String s[]) { try { System.out.println(“Truoc ngoai le"); staticLengthmethod(); System.out.println(“Sau ngoai le"); } catch(NullPointerException ne) { System.out.println(“Da xay loi"); } finally { System.out.println(“Trong finally"); } } try { // Khoi lenh co the sinh ngoai le } catch(ExceptionType e) { // Bat va xu ly ngoai le } finally { /* Thuc hien cac cong viec can thiet du ngoai le co xay hay khong */ } static void staticLengthmethod() { System.out.println(str.length()); } 35 } 36 8/24/2011 Nội dung 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 -"); } } Ngoại lệ Bắt xửlý ngoại lệ Ủ y nhiệ m ngoạ i lệ Tạo ngoại lệtựđị nh nghĩa 37 38 3.1 Ủy nhiệm ngoại lệ Hai cách làm việc với ngoại lệ Xửlý Ủ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 } 39 3.1 Ủy nhiệm ngoại lệ(3) 40 public class DelegateExceptionDemo { public static void main(String args[]){ int num = calculate(9,3); System.out.println(“Lan 1: ” + num); num = calculate(9,0); System.out.println(“Lan 2: ” + 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; } } Ví dụ class Test { public void myMethod(int param) { if (param < 10) { throw new RuntimeException("Too low!"); } //Blah, Blah, Blah } } Không lỗi? 41 42 8/24/2011 public class DelegateExceptionDemo { public static void main(String args[]){ int num = calculate(9,3); System.out.println(“Lan 1: ” + num); num = calculate(9,0); System.out.println(“Lan 2: ” + 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; } } 43 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; } 44 } 3.1 Ủy nhiệm ngoại lệ(4) 3.2 Lan truyền ngoại lệ Ủy nhiệm nhiều ngoại lệ C() 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 } B() A() main() C() tung ngoại lệ B() A() main() Nếu C() gặp lỗi tung ngoại lệnhưng C() lại không xửlý ngoại lệnày, th% nơi có thểxửlý nơi mà C() gọi, phương thức B() … 45 3.3 Kếthừa ủy nhiệm ngoại lệ 46 3.3 Kếthừa ủy nhiệm ngoại lệ(2) class Disk { void readFile() throws EOFException {} } class FloppyDisk extends Disk { void readFile() throws IOException {} } Khi override phương thức lớp cha, phương thức ởlớp không phép tung ngoại lệmới class Disk { void readFile() throws IOException {} } class FloppyDisk extends Disk { void readFile() throws EOFException {} } 47 48 8/24/2011 Nội dung 3.4 Ưu điểm ủy nhiệm ngoạilệ Ngoại lệ Bắt xửlý ngoại lệ Ủy nhiệm ngoại lệ Tạ o ngoạ i lệ tự đị nh nghĩ a 49 49 Tạo ngoại lệtựđị nh nghĩa 50 Sử dụng ngoại lệ người dùng định nghĩa public class MyException extends Exception { public MyException(String msg) { super(msg); } public MyException(String msg, Throwable cause){ super(msg, cause); } } public class FileExample { public void copyFile(String fName1,String fName2) throws MyException { if (fName1.equals(fName2)) throw new MyException("File trung ten"); // Copy file System.out.println("Copy completed"); } } 51 52 Sử dụng ngoại lệ người dùng định nghĩa Bắt xửlý ngoại lệ public class Test { public static void main(String[] args) { FileExample obj = new FileExample(); try { String a = args[0]; String b = args[1]; obj.copyFile(a,b); } catch (MyException e1) { System.out.println(e1.getMessage()); } catch(Exception e2) { System.out.println(e2.toString()); } } } 53 ... Nhược điểm Nội dung Ngoại lệ Bắ t xử lý ngoạ i lệ Ủy nhiệm ngoại lệ Tạo ngoại lệtựđị nh nghĩa 10 2.1 Mục đích x lý ngoại lệ 2.1 Mục đích x lý ngoại lệ( 2) Khi xảy ngoại lệ, ch xử lý thích hợp? …………... “DIVISION BY ZERO” Khối xử lý lỗi EXIT: END 11 12 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 cách 13 2.3 X lý ngoại lệtrong Java 14 2.3 X lý ngoại lệtrong Java (2)... System.out.println(" - File End -"); } } Ngoại lệ Bắt x lý ngoại lệ Ủ y nhiệ m ngoạ i lệ Tạo ngoại lệtựđị nh nghĩa 37 38 3.1 Ủy nhiệm ngoại lệ Hai cách làm việc với ngoại lệ X lý Ủy nhiệm cho vịtrí gọi nó:

Ngày đăng: 11/11/2015, 11:53

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan