Validate input data
Handle exceptions
How to catch exceptions
The compiler needs to know that you know you're calling a risky method
If you wrap the risky code in something called a try/cath, the compiler will relax.
A try/catch block tells the compiler that you know an exceptional thing could happen in the method you're calling, and that you're prepared to handle it. That compiler doesn't care how you handle it; it cares only that you say you're taking care of it.
The syntax for the try statement
try { statements } catch(ExceptionClass exceptionName) { statements }
How to catch exceptions
- In a try statement (or try/catch statement):
- you code any statements that may throw an exception in a try block
- you can code a catch block that will handle any exceptions that may occur in the try block
- When an exception occurs, any remaining statements in the try block are skipped and the statements in the catch block are executed.
- Any variables or objects that are used in both the try/catch blocks must be created before the try/catch blocks so both the try/catch blocks can access them.
- If you use a catch block to catch a specific type of exception, you must also import the package that contains that exception class.
Two ways to import the InputMismatchException class
import java.util.InputMismatchException; import java.util.*;
A try statement that catches an InputMismatchException
double subtotal = 0.0; try { System.out.print("Enter subtotal: "); subtotal = sc.nextDouble(); } catch(InputMismatchException e) { sc.next(); // discard the incorrectly entered double System.out.println("Error! Invalid number. Try again.\n"); continue; // jump to the top of the loop }
Using the try/catch
import java.util.Scanner; import java.util.InputMismatchException; public class InvoiceApp { public static void main(String[] args) { // welcome the user to the program System.out.println("Welcome to the Invoice Total Calculator"); System.out.println(); // print a blank line // create a Scanner object named sc Scanner sc = new Scanner(System.in); // perform invoice calculations until choice isn't equal to "y" or "Y" String choice = "y"; while (choice.equalsIgnoreCase("y")) { double subtotal = 0.0; try { // get the invoice subtotal from the user System.out.print("Enter subtotal: "); subtotal = sc.nextDouble(); } catch(InputMismatchException e) { sc.next(); // discard the incorrectly entered double System.out.println("Error! Invalid number.Try again.\n"); continue; // jump to the top of the loop } // calculate the discount amount and total double discountPercent= 0.0; if (subtotal >= 200) discountPercent = .2; else if (subtotal >= 100) discountPercent = .1; else discountPercent = 0.0; double discountAmount = subtotal * discountPercent; double total = subtotal - discountAmount; // display the discount amount and total String message = "Discount percent: " + discountPercent + "\n" + "Discount amount: " + discountAmount + "\n" + "Invoice total: " + total + "\n"; System.out.println(message); // see if the user wants to continue System.out.print("Continue? (y/n): "); choice = sc.next(); System.out.println(); } } }
If you can't recover from the exception, at least get a stack trace
import java.util.Scanner; import java.util.InputMismatchException; public class InvoiceApp { public static void main(String[] args) { // welcome the user to the program System.out.println("Welcome to the Invoice Total Calculator"); System.out.println(); // print a blank line // create a Scanner object named sc Scanner sc = new Scanner(System.in); // perform invoice calculations until choice isn't equal to "y" or "Y" String choice = "y"; while (choice.equalsIgnoreCase("y")) { double subtotal = 0.0; try { // get the invoice subtotal from the user System.out.print("Enter subtotal: "); subtotal = sc.nextDouble(); } catch(InputMismatchException e) { sc.next(); // discard the incorrectly entered double System.out.println("Error! Invalid number.Try again.\n"); e.printStackTrace(); // get a stack trace that all exceptions inherit } // calculate the discount amount and total double discountPercent= 0.0; if (subtotal >= 200) discountPercent = .2; else if (subtotal >= 100) discountPercent = .1; else discountPercent = 0.0; double discountAmount = subtotal * discountPercent; double total = subtotal - discountAmount; // display the discount amount and total String message = "Discount percent: " + discountPercent + "\n" + "Discount amount: " + discountAmount + "\n" + "Invoice total: " + total + "\n"; System.out.println(message); // see if the user wants to continue System.out.print("Continue? (y/n): "); choice = sc.next(); System.out.println(); } } }