Lecter Java: Program design - Chapter 10: Exceptions

Java treatment of an exception If exception occurs and a handler is in effect Flow of control is transferred to the handler After handler completes flow of control continues with the statement following the handler If exception occurs and there is no handler for it The program terminates

ppt29 trang | Chia sẻ: candy98 | Lượt xem: 477 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Lecter Java: Program design - Chapter 10: Exceptions, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
ExceptionsCopyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.ExceptionAbnormal event occurring during program executionExamplesManipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);Improper array subscripting int[] a = new int[3]; a[4] = 1000; Improper arithmetic operations a[2] = 1000 / 0; Java treatment of an exceptionIf exception occurs and a handler is in effectFlow of control is transferred to the handlerAfter handler completes flow of control continues with the statement following the handlerIf exception occurs and there is no handler for itThe program terminatesTaskPrompt and extract the name of a fileFrom that file, two integer values are to be extractedCompute and display the quotient of the valuesImplementationpublic static void main(String[] args) throws IOException { Scanner stdin = new Scanner(System.in); System.out.print("Filename: "); String s = stdin.nextLine(); File file = new File(s); Scanner fileIn = new Scanner(file); int a = fileIn.nextInt(); int b = fileIn.nextInt(); System.out.println( a / b );}What can go wrong?public static void main(String[] args) throws IOException { Scanner stdin = new Scanner(System.in); System.out.print("Filename: "); String s = stdin.nextLine(); File file = new File(s); Scanner fileIn = new Scanner(file); int a = fileIn.nextInt(); int b = fileIn.nextInt(); System.out.println( a / b );}How can we deal with the problems?public static void main(String[] args) throws IOException { Scanner stdin = new Scanner(System.in); System.out.print("Filename: "); String s = stdin.nextLine(); File File = new File(s); Scanner fileIn = new Scanner(file);( int a = fileIn.nextInt()); int b = fileIn.nextInt()); System.out.println( a / b );}Exception handlersCode that might generate an exception is put in a try blockIf there is no exception, then the handlers are ignoredFor each potential exception type there is a catch handlerWhen handler finishes the program continues with statement after the handlerstry { Code that might throw exceptions of types E or F}catch (E e) { Handle exception e}catch (F f) { Handle exception f}More codeIntroduce try-catch blockspublic static void main(String[] args) throws IOException { Scanner stdin = new Scanner(System.in); System.out.print("Filename: "); String s = stdin.nextLine(); File file = new File(s); Scanner fileIn = new Scanner(file); int a = fileIn.nextInt(); int b = fileIn.nextInt()); System.out.println( a / b );}Setting up the file stream processingScanner stdin = new Scanner(System.in); System.out.print("Filename: "); String s = stdin.nextLine();// set up file stream for processingScanner fileIn = null; try { File file = new File(s); fileIn = new Scanner(file); } catch (FileNotFoundException e) { System.err.println(s + “: Cannot be opened for reading"); System.exit(0); }How come the main() throws expression did not indicate it could throw a FileNotFoundException?Getting the inputstry { int a = fileIn.nextInt(); int b = fileIn.nextInt(); System.out.println( a / b ); } catch (InputMismatchException e) { System.err.println(s + ": contains nonnumeric inputs"); System.exit(0); } Converting the inputstry { int a = fileIn.nextInt(); int b = fileIn.nextInt(); System.out.println( a / b ); } catch (InputMismatchException e) { System.err.println(s + ": contains nonnumeric inputs"); System.exit(0); } catch (NoSuchElementException e) { System.err.println(s + ": does not contain two inputs"); System.exit(0); } catch (ArithmeticException e) { System.err.println(s + ": unexpected 0 input value"); System.exit(0); } } Run time exceptionsJava designers realizedRuntime exceptions can occur throughout a programCost of implementing handlers for runtime exceptions typically exceeds the expected benefitJava makes it optional for a method to catch them or to specify that it throws themHowever, if a program does not handle its runtime exceptions it is terminated when one occursCommands type and catMost operating systems supply a command for listing the contents of filesWindows: typeUnix, Linux, and OS X: cattype filename1 filename2 filenamenDisplays the contents of filename1 filename2 and filenamen to the console windowPossible method main() for Type.javapublic static void main(String[] args) { for (int i = 0; i = 0) { balance = n; } else { throw new NegativeAmountException("Bad balance"); }}Class BankAccount// getBalance(): return the current balance public int getBalance() { return balance;}// addFunds(): deposit amount n public void addFunds(int n) throws NegativeAmountException { if (n >= 0) { balance += n; } else { throw new NegativeAmountException("Bad deposit"); } }Class BankAccount// removeFunds(): withdraw amount npublic void removeFunds(int n) throws NegativeAmountException { if (n < 0) { throw new NegativeAmountException("Bad withdrawal"); } else if (balance < n) { throw new NegativeAmountException("Bad balance"); } else { balance -= n; }}Using NegativeAmountExceptionSystem.out.print("Enter deposit: ");try { int deposit = stdin.nextInt(); savings.addFunds(deposit);}catch (NegativeAmountException e) { System.err.println(“Cannot deposit negative funds“); System.exit(0);}Using NegativeAmountExceptionSystem.out.print("Enter withdrawal: ");try { int withdrawal = stdin.nextInt(); savings.removeFunds(withdrawl);}catch (NegativeAmountException e) { if (e.message().equals("Bad withdrawal")) System.err.println(“Cannot withdraw negative funds“); else { System.err.println("Withdrawal cannot leave " "negative balance"); } System.exit(0);}