1 / 24

Java Programming: From the Beginning

Java Programming: From the Beginning. Chapter 8 Section 1 Exceptions. 8.1 Exceptions. When a Java program performs an illegal operation, an exception happens.

jaegar
Download Presentation

Java Programming: From the Beginning

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. Java Programming: From the Beginning Chapter 8 Section 1 Exceptions

  2. 8.1 Exceptions • When a Java program performs an illegal operation, an exception happens. • Java provides a way for a program to detect that an exception has occurred and execute statements that are designed to deal with the problem. • This process is called exception handling.

  3. Common Exceptions • There are many kinds of exceptions, each with a different name. • Common exceptions: • ArithmeticException • NumberFormatException • Trying to divide by zero causes an ArithmeticException:

  4. Common Exceptions • Using zero as the right operand in a remainder operation also causes an ArithmeticException: i = j % k; // ArithmeticException occurs if k = 0

  5. Converting Strings to Integers • Attempting to convert a string to an int value using Integer.parseInt may fail: • Converting "123" will succeed. • Converting "duh" will fail, causing a NumberFormatException to be thrown.

  6. Converting Strings to Integers • If the string contains user input, it’s often a good idea to have the user re-enter the input.

  7. Handling Exceptions • When an exception occurs (is thrown), the program has the option of catching it. • In order to catch an exception, the code in which the exception might occur must be enclosed in a try block. • After the try block comes a catch block that catches the exception (if it occurs) and performs the desired action.

  8. Handling Exceptions • The try and catch blocks together form a single statement, which can be used anywhere in a program that a statement is allowed: try block catch (exception-typeidentifier) block • exception-type specifies what kind of exception the catch block should handle. • identifier is an arbitrary name.

  9. Handling Exceptions • If an exception is thrown within the try block, and the exception matches the one named in the catch block, the code in the catch block is executed. • If the try block executes normally—without an exception—the catch block is ignored. • An example of try and catch blocks: try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); }

  10. Converting Strings to Integers • A robust program should provide a catchblock to handle the exception: try { n = Integer.parseInt(str); } catch (NumberFormatException e) { // Handle exception }

  11. Converting Strings to Numbers • Putting the try and catch blocks in a loop allows the user multiple attempts to enter a valid number: while (true) { String userInput = JOptionPane.showInputDialog(“Enter a Number”); try { n = Integer.parseInt(userInput); break; // Input was valid; exit the loop } catch (NumberFormatException e) { System.out.println("Not an integer; try again."); } }

  12. Converting Strings to Numbers • Putting the try and catch blocks in a loop allows the user multiple attempts to enter a valid number: boolean switch=true; while (switch) { String userInput = JOptionPane.showInputDialog(“Enter a Number”); try { n = Integer.parseInt(userInput); switch=false; } catch (NumberFormatException e) { System.out.println("Not an integer; try again."); } }

  13. Accessing Information About an Exception • When an exception occurs, Java creates an “exception object” that contains information about the error. • The identifier in a catch block (typically e) represents this object. • Every exception object contains a string. The getMessage method returns this string: e.getMessage()

  14. Terminating the Program After an Exception • When an exception is thrown, it may be necessary to terminate the program. • Ways to cause program termination: • Call the System.exit method.

  15. Terminating the Program After an Exception • Adding a call of System.exit to a catch block will cause the program to terminate: try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); System.exit(-1); } • A program that terminates abnormally should supply a nonzero argument (typically –1) to System.exit.

  16. Variables and try Blocks • Be careful when declaring variables inside a try (or catch) block. A variable declared inside a block is always local to that block. • An example: try { int quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); } • quotient is local to the try block; it can’t be used outside the try block.

  17. Variables and try Blocks • There’s another trap associated with try blocks. • Suppose that the quotient variable is declared immediately before the try block: int quotient; try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); } • The compiler won’t allow the value of quotient to be accessed later in the program, because no value is assigned to quotient if the exception occurs.

  18. Variables and try Blocks • The solution is often to assign a default value to the variable: int quotient = 0; // Default value try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); }

  19. Accessing Information About an Exception • An example of printing the message inside an exception object: try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println(e.getMessage()); } • If the exception is thrown, the message might be: / by zero

  20. Multiple catch Blocks • A try block can be followed by more than one catch block: try { quotient = Integer.parseInt(str1) / Integer.parseInt(str2); } catch (NumberFormatException e) { System.out.println("Error: Not an integer"); } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); } • When an exception is thrown, the first matching catch block will handle the exception.

  21. Checked Exceptions Versus Unchecked Exceptions • Exceptions fall into two categories. • A checked exception must be dealt with by the program. The compiler will produce an error if there is no tryblock and catch block to handle the exception. • An unchecked exception can be ignored by the programmer; there’s no need to usetry and catchto handle the exception.

  22. Checked Exceptions VersusUnchecked Exceptions • Some unchecked exceptions represent disasters so severe that there’s no hope of continuing program execution. • Others represent errors that could potentially occur at hundreds of places in a program, including ArithmeticException, NullPointerException, and NumberFormatException. • Checked exceptions represent conditions that the programmer should be able to anticipate and deal with.

  23. Using Exceptions Properly • try and catch blocks aren’t meant to be used as ordinary control structures. • In most cases, it’s better to test for an error before it occurs rather than wait until it happens and then catch the resulting exception. • Consider the following loop: while (n != 0) { r = m % n; m = n; n = r; }

  24. Using Exceptions Properly • The loop could be written in the following way: try { while (true) { r = m % n; m = n; n = r; } } catch (ArithmeticException e) {} • The loop still works, but it’s harder to figure out when the loop will terminate. Also, the code is longer and more deeply nested.

More Related