240 likes | 457 Views
Java Programming: From the Beginning. Chapter 8 Section 1 Exceptions. 8.1 Exceptions. When a Java program performs an illegal operation, an exception happens.
E N D
Java Programming: From the Beginning Chapter 8 Section 1 Exceptions
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.
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:
Common Exceptions • Using zero as the right operand in a remainder operation also causes an ArithmeticException: i = j % k; // ArithmeticException occurs if k = 0
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.
Converting Strings to Integers • If the string contains user input, it’s often a good idea to have the user re-enter the input.
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.
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.
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"); }
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 }
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."); } }
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."); } }
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()
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.
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.
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.
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.
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"); }
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
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.
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.
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.
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; }
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.