Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 53 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
53
Dung lượng
468,5 KB
Nội dung
1 Chapter 5. ExceptionHandling ITSS Java Programming CAO Tuan-Dung, HUT 2 What is an exception? Exceptional event Error that occurs during runtime Cause normal program flow to be disrupted Examples Divide by zero errors Accessing the elements of an array beyond its range Invalid input Hard disk crash Opening a non-existent file Heap memory exhausted 3 Example // divide by zero class DivByZero { public static void main(String args[]) { System.out.println(3/0); System.out.println(“Pls. print me.”); } } // array out of bound int array[] = new int[2]; array[0] = 1; array[1] = 2; array[2] = 3; // execute method of object that does not exist String s = null; s.length(); Exception Object ArithmeticException Exception Object ArrayIndexOutOfBoundException Exception Object NullPointerException 4 Default exceptionhandling Displays this error message Exception in thread "main" java.lang.ArithmeticException: / by zero at DivByZero.main(DivByZero.java:3) Default exception handler Provided by Java runtime Prints out exception description Prints the stack trace Hierarchy of methods where the exception occurred Causes the program to terminate 5 What Happens When an Exception Occurs? When an exception occurs within a method, the method creates an exception object and hands it off to the runtime system Creating an exception object and handing it to the runtime system is called “throwing an exception” Exception object contains information about the error, including its type and the state of the program when the error occurred 6 Lab: Exception Run this program and observe the exceptions exceptions of the type that is different according to the specified value. prompt> java Exceptions <ExceptionNO> ExceptionNO:1→ArrayIndexOutOfBoundsEx ception ExceptionNO:2→NullPointerException ExceptionNO:3→ArithmeticException 7 Exception.java class Exceptions { public static void main(String args[])throws Exception { if(args.length != 1) { System.out.println("Usage : java Exceptions <ExceptionNO>"); System.out.println("ExceptionNO:1→ArrayIndexOutOfBoundsException"); System.out.println("ExceptionNO:2→NullPointerException"); System.out.println("ExceptionNO:3→ArithmeticException"); System.exit(1); } int exceptionNo = Integer.parseInt( args[0] ); // Generate exception that is different according to the input value switch(exceptionNo) { case 1: // ArrayIndexOutOfBoundsException int array[] = new int[3]; array[3] = 100; break; 8 Exception.java case 2: // NullPointerException String s = null; int length = s.length(); break; case 3: // ArithmeticException int x = 100; int y = 0; int z = x / y; break; default: System.out.println(“It doesn‘t match with ExceptionNO."); } } } 9 System exceptions Exceptions provided by Java language 10 Exceptionhandling To handle an exception in a program, the line that throws the exception is executed within a try block A try block is followed by one or more catch clauses Each catch clause has an associated exception type and is called an exception handler When an exception occurs, processing continues at the first catch clause that matches the exception type [...]... ExceptionNO:1→ArrayIndexOutOfBoundsException ExceptionNO:2→NullPointerException ExceptionNO:3→ArithmeticException 12 ExceptionsTryCatch .java class ExceptionsTryCatch { public static void main(String args[])throws Exception { if(args.length != 1) { System.out.println("Usage : java Exceptions "); System.out.println("ExceptionNO:1→ArrayIndexOutOfBoundsException"); System.out.println("ExceptionNO:2→NullPointerException");.. .Exception handling Syntax: try { } catch ( ) { } } catch ( ) { } 11 Example This program shows how the exceptions in previous example are caught and processed Usage: prompt> java ExceptionsTryCatch ExceptionNO:1→ArrayIndexOutOfBoundsException... LimitException extends Exception{ Throwable // Constructor public LimitException(String message){ super(message); } :// Addition of necessary attribute and method Exception } XXException XX 2Exception XX 1Exception 16 Error processing in User define exception Flow of exception handling Execute a processing that has the possibility to generate an error A systematic or operational error occurs An exception. .. (4) Exception object is notified and error processing is done (2) Error occurred Ex ce System.out.println(e.getMessage()) ; Exception Object (3) Exception object is generated 18 Method that throws exception [Modifier] Return value type Method name(Argument…) throws Exception Class, { throw Exception Object declare the exception type that generating Exception Object } the method might throw Exception handling. .. System.out.println("ExceptionNO:2→NullPointerException"); System.out.println("ExceptionNO:3→ArithmeticException"); System.exit(1); } int exceptionNo = Integer.parseInt( args[0] ); try { // Generate exception that is different according to the input value switch(exceptionNo) { case 1: // ArrayIndexOutOfBoundsException int array[] = new int[3]; array[3] = 100; break; 13 ExceptionsTryCatch .java case 2: // NullPointerException String s = null; int... definition Exception Classes that define exceptions are related by inheritance, forming an exception class hierarchy All error and exception classes are descendents of the Throwable class A programmer can define an exception by extending the Exception class or one of its descendants The parent class used depends on how the new exception will be used 15 User definition Exception public class LimitException... // ArithmeticException int x = 100; int y = 0; int z = x / y; break; default: System.out.println(“It doesn‘t match with ExceptionNO."); } }catch(ArrayIndexOutOfBoundsException e){ System.out.println(“ArrayIndexOutOfBoundsException is caught "); }catch(NullPointerException e){ System.out.println(“NullPointerException is caught."); catch(ArithmeticException e){ System.out.println(“ArithmeticException is... generated The exception object is notified,and the error processing according to the exception object is executed 17 Error processing in User define exception try { (1) Execute a processing that has the possibility to generate an error obj.withdraw(10000000); } catch (LimitException e){ public void withdraw(long money) throws LimitException, InsufficiencyException { if (money>=1000000) throw new LimitException... System.out.println("Balance : " + balance); } } 23 Solution: Bank .java // Exception of exceeded withdrawal amount limit class LimitException extends Exception { public LimitException(String message) { super(message); } } // Insufficient balance exception class InsufficiencyException extends Exception { public InsufficiencyException(String message) { super(message); } } 24 Wrapper Class Some Facts: Primitive data types are... LimitException, InsufficiencyException { if(money >= 1000000) { throw new LimitException(“Withdrawal amount limit is exceeded"); } if(money > balance) { throw new InsufficiencyException("Insufficient balance"); } balance -= money; } // Display of account information public void print() { System.out.println("ID : " + id); System.out.println("Balance : " + balance); } } 23 Solution: Bank .java // Exception . null; s.length(); Exception Object ArithmeticException Exception Object ArrayIndexOutOfBoundException Exception Object NullPointerException 4 Default exception handling Displays this error message Exception. <ExceptionNO> ExceptionNO:1→ArrayIndexOutOfBoundsEx ception ExceptionNO:2→NullPointerException ExceptionNO:3→ArithmeticException 7 Exception .java class Exceptions { public static void main(String args[])throws Exception { if(args.length. match with ExceptionNO."); } } } 9 System exceptions Exceptions provided by Java language 10 Exception handling To handle an exception in a program, the line that throws the exception