Java Programming I on YouTube:
https://www.youtube.com/playlist?list=PLLIqcoGpl73iaXAtS_-V_Xdx3mhTzPwb5
There are three types of errors that may occur in Java programming:
Syntax errors (or compile-time errors) -- violate Java syntax rules or rules for Java statements (e.g. code may require an exception handler.)
Runtime errors -- the syntax is okay, but these errors throw exceptions that stop the execution of the application.
Logic errors -- the code that produces the wrong results without syntax or runtime errors, e.g. wrong formula to convert inches to centimeters.
Misspelling keywords.
Forgetting to declare a data type for a variable.
Forgetting an opening or closing parenthesis, bracket, brace, or comment character.
Forgetting to code a semicolon at the end of a statement.
Forgetting an opening or closing quotation mark.
Using a reserved word, global property, or global method as an identifier.
Not checking the value before processing it. For example, user enters non-numeric value instead of a number.
Division by zero
Misspelling or incorrectly capitalizing an identifier, then using a wrong variable as a result.
Using one equals sign (=) instead of two (==) when testing numeric and boolean values for equality.
Using two equals signs (==) instead of equals()/equalsIgnoreCase() methods to test two strings for equality.
The Java programming language uses exceptions to handle errors and other exceptional events
Some of the classes in the Exception hierarchy
Exception RuntimeException NoSuchElementException InputMismatchException IllegalArgumentException NumberFormatException ArithmeticException NullPointerException
After an InputMismatchException has been thrown, the console output window might look like this:
Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:909) at java.util.Scanner.next(Scanner.java:1530) at java.util.Scanner.nextDouble(Scanner.java:2456) at InvoiceApp.main(InvoiceApp.java:20)
The program prints a stack trace and exits.
Four methods that might throw an exception:
Class Method Throws --------- ------------------- ----------------------- Scanner nextInt() InputMismatchException Scanner nextDouble() InputMismatchException Integer parseInt(String) NumberFormatException Double parseDouble(String) NumberFormatException
The syntax for the try statement
try { statements } catch (ExceptionClass exceptionName) { statements }
A try statement anticipates that an exception may occur
A catch block to provide a handler for the exception
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 }
Multiple catch blocks are allowed:
try { } catch (ExceptionType name) { } catch (ExceptionType name) { }
For example,
try { } catch (FileNotFoundException e) { System.err.println("FileNotFoundException: " + e.getMessage()); throw new SampleException(e); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); }
The finally block executes
when the try block exits normally, or
when an exception occurs.
Therefore, the finally block always executes when the try block exits.
try { } catch (ExceptionType name) { } catch (ExceptionType name) { } finally { // always executes }
The finally block is a key tool for preventing resource leaks. Place the code in a finally block when closing a file or recovering other resources
There are methods of the Scanner class that you can use to validate data:
hasNext( )
hasNextInt( )
hasNextDouble( )
nextLine( )
double subtotal = 0.0; System.out.print("Enter subtotal: "); if (sc.hasNextDouble()) { subtotal = sc.nextDouble(); } else { sc.nextLine(); // discard the entire line System.out.println( "Error! Invalid number. Try again.\n"); continue; // jump to the top of the loop }
Console output:
Enter subtotal: $100 Error! Invalid number. Try again. Enter subtotal:
if (customerType != null)
{
if (customerType.equals("R"))
discountPercent = .4;
}
Code that gets a valid double value within a specified range
Scanner sc = new Scanner(System.in); double subtotal = 0.0; boolean isValid = false; while (isValid == false) { // get a valid double value System.out.print("Enter subtotal: "); if (sc.hasNextDouble()) { subtotal = sc.nextDouble(); isValid = true; } else { System.out.println( "Error! Invalid number. Try again."); } sc.nextLine(); // discard any other data entered on the line // check the range of the double value if (isValid == true && subtotal <= 0) { System.out.println( "Error! Number must be greater than 0."); isValid = false; } else if (isValid == true && subtotal >= 10000) { System.out.println( "Error! Number must be less than 10000."); isValid = false; } }
A method that gets a valid numeric format
public static double getDouble(Scanner sc, String prompt) { double dbl = 0.0; boolean isValid = false; while (isValid == false) { System.out.print(prompt); if (sc.hasNextDouble()) { dbl = sc.nextDouble(); isValid = true; } else { System.out.println( "Error! Invalid number. Try again."); } sc.nextLine(); // discard any other data } return dbl; }
Each Java program must follow this rule:
if a block of code can throw an exception, such block of code must be
(a) wrapped by a try statement that catches exceptions and handles them in the corresponding catch blocks.
try { //a block of code that can throw an exception } catch (ExceptionType name) { }
(b) enclosed in a method with the throws clause, for example,
public void saveFile() throws IOException {
//a block of code that can throw an exception
}///saveFile
Otherwise, if Catch or Specify requirement is not honored, the code will not compile.