1 / 14

10.2 – Zero.java

10.2 – Zero.java. //******************************************************************** // Zero.java Java Foundations // Demonstrates an uncaught exception. //******************************************************************** public class Zero {

naava
Download Presentation

10.2 – Zero.java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 10.2 – Zero.java //******************************************************************** // Zero.java Java Foundations // Demonstrates an uncaught exception. //******************************************************************** public class Zero { //----------------------------------------------------------------- // Deliberately divides by zero to produce an exception. //----------------------------------------------------------------- public static void main (String[] args) { int numerator = 10; int denominator = 0; System.out.println ("Before the attempt to divide by zero."); System.out.println (numerator / denominator); System.out.println ("This text will not be printed."); } }

  2. 10.1 – Exceptions vs Errors • An exceptionis an object describing unusual or erroneous situation • Division by 0 in computing expression (ArithmeticException) • Array index out of bounds (IndexOutOfBoundsException) • Null pointer cannot be followed (NullPointerException) • I/O problems (e.g., no space on disk to save file, file not found: IOException) • No permissions to do something (e.g., to save a file: FileNotFoundException) • Exceptions are “thrown”by a program, and may be “caught”and “handled”by another part of the program • (An erroris also an object, but it represents a unrecoverable situation and should not be caught)

  3. 10.2 – ZeroPlus.java //******************************************************************** // ZeroPlus.java // Demonstrates an exception caught and HANDLED. //******************************************************************** public class ZeroPlus { //----------------------------------------------------------------- // Deliberately divides by zero to catch an exception. //----------------------------------------------------------------- public static void main (String[] args) { int numerator = 10; int denominator = 0; System.out.println ("Before the attempt to divide by zero."); try{ System.out.println (numerator / denominator); }catch (ArithmeticException arex) { System.out.println ("Attempt to divide by zero. Not good."); } System.out.println ("This text will NOW be printed."); } }

  4. 10.3 – The try Statement • To handle an exception, the line that throws the exception is executed within a try block • A try block is followed by one or more catch clauses • When an exception occurs, processing continues at the first catch clause that matches the exception type // here is code that // should generate no exceptions try {// code to monitor // several possible things // that can go wrong // goes here}catch (ExceptionTypeA ex) {//handler for ExceptionTypeA}catch (ExceptionTypeB ex) {//handler for ExceptionTypeB}// after a catch, continue here

  5. Using Exceptions in an “exceptional” way ;-) D I S T Z // Counts the number of product codes that are entered // with a zone of R and district greater than 2000. try { zone = code.charAt(9); district = Integer.parseInt(code.substring(3, 7)); valid++; if (zone == 'R' && district > 2000) banned++; } catch (StringIndexOutOfBoundsException exception) { System.out.println ("Improper code length: " + code); } catch (NumberFormatException exception) { System.out.println ("District is not numeric: " + code); }

  6. 10.5 EC Hierarchy

  7. Asserted in the throws clause //******************************************************************** // TestData.java Java Foundations // Demonstrates asserted clause. //******************************************************************** import java.util.Random; import java.io.*; public class TestData { //----------------------------------------------------------------- // Will read/write to a file and things can go bad. //----------------------------------------------------------------- public static void main (String[] args) throws IOException { String file = "test.dat"; // more on FileIO shortly (more…)

  8. 10.5 – An exception is either checkedor unchecked • An unchecked exception does not require explicit handling • The only unchecked exceptions in Java are objects of type RuntimeExceptionor any of its descendants • Errors are similar to RuntimeException and its descendants in that • Errors should not be caught • Errors do not require a throws clause • A checked exception requires explicit handling. It must • be caught by a method, (using try-catch block) or • be asserted in the throws clauseof any method that may throw or propagate it • The compiler will issue error if a checked exception is not caught or asserted in a throws clause

  9. You can create your own Exceptions // Demonstrates the ability to define an exception. import java.util.Scanner; public class CreatingExceptions { // Creates an exception object and possibly throws it. public static void main (String[] args) throws OutOfRangeException { final int MIN = 25, MAX = 40; Scanner scan = new Scanner (System.in); OutOfRangeException problem = new OutOfRangeException ("Input value is out of range."); System.out.print ("Enter an integer b/w" + MIN + " & " + MAX ); int value = scan.nextInt(); // Determine if the exception should be thrown if (value < MIN || value > MAX) throw problem; System.out.println ("End of main method."); // may never reach } }

  10. 10.5 – OutOfRangeException.java //******************************************************************** // OutOfRangeException.java Java Foundations // // Represents an exceptional condition in which a value is out of // some particular range. //******************************************************************** public class OutOfRangeException extends Exception { //----------------------------------------------------------------- // Sets up the exception object with a particular message. //----------------------------------------------------------------- OutOfRangeException (String message) { super (message); } }

  11. Displaying the contents of a file /* Read in the contents of a file line by line, * and print out each line after it is read in. * Stop when the end of the file is reached. */ public staticvoid displayFile (String inFileName) { try { Scanner fileScan = new Scanner (new File(inFileName)); while (fileScan.hasNext()) { String line = fileScan.nextLine(); System.out.println (line); System.out.println(); } } } catch (IOException ex) { System.out.println(ex); } }

  12. Displaying the contents of a web page /* Read in the contents of a web page line by line, * and print out each line after it is read in. * Stop when the end of the web page is reached. */ public staticvoid displayWebPage (String urlName) { try { URL u = new URL(urlName); Scanner urlScan = new Scanner( u.openStream() ); // will throw exception while (urlScan.hasNext()) { String line = urlScan.nextLine(); System.out.println (line); System.out.println(); } } catch (IOException ex) { System.out.println(ex); } }

  13. Displaying contents read in from keyboard /* Read in lines of text from the keyboard, * and print out each line after it is read in. * Stop when the user enters “quit”. */ public staticvoid displayKeyboardInput () { try { Scanner keyboardScan = new Scanner (System.in); do { String line = keyboardScan.nextLine(); System.out.println (line); System.out.println(); } while (keyboardScan.hasNext()); } catch (IOException ex) { System.out.println(ex); } }

  14. Copying a File /* Copies an input file to an output file. * Displays an error message if the output file cannot be created. */ public staticvoid copyFile (String inFileName, String outFileName) { try { Scanner reader=new Scanner (new File(inFileName)); PrintWriter writer=new PrintWriter (new File(outFileName)) while (reader.hasNext()) { // Read and write line to output file writer.println(reader.nextLine());} } catch (IOException ex) { System.out.println(ex); // Handle file-not-found } }

More Related