1. The Scanner class
Scanner is a new feature in Java5. You can use the Scanner class to retrieve input from the user, and use the next() and nextLine() methods of the Scanner class to retrieve input strings. Before reading, we usually need to use hasNext and hasNextLine to determine whether there is any input data.
Here is the basic syntax for creating Scanner objects:
Scanner s = new Scanner(System.in);
1
Next () differs from nextLine()
next():
1, must read valid characters before you can end the input.
2. The next() method automatically removes whitespace encountered before entering valid characters.
3. Only after a valid character is entered, the following blank is used as the delimiter or terminator.
4. Next () does not get a string with Spaces.
NextLine () :
1
Enter is used to compare overnight foreign exchange interest rates
http://www.fx61.com/interest.html
Terminator, that is, the nextLine() method returns all characters up to the input carriage return.
2. You can get whitespace.
The Scanner class also supports typing int or float data, but it is best to validate it with the hasNextXxx() method before reading it using nextXxx() :
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Receive data from keyboard
int i = 0;
Float f = 0.0 f;
System.out.print(” Input integer: “);
if (scan.hasNextInt()) {
// Check whether the input is an integer
i = scan.nextInt();
// Accept integers
System.out.println(” integer data: “+ I);
} else {
// Enter incorrect information
System.out.println(” Input is not an integer!” );
}
System.out.print(” Enter decimal: “);
if (scan.hasNextFloat()) {
// Determine if the input is a decimal
f = scan.nextFloat();
// Accept decimals
System.out.println(” decimal: “+ f);
} else {
// Enter incorrect information
System.out.println(” Input is not a decimal!” );
}
scan.close();
}
}
The output of the above program is as follows:
$ javac ScannerDemo.java
$ java ScannerDemo
Enter the integer 12
Integer data: 12
Enter the decimal number: 1.2
Decimal data: 1.2
2. Java exception handling
Exceptions are some errors in a program, but not all errors are exceptions, and errors can sometimes be avoided.
To understand how Java exception handling works, you need to understand three types of exceptions:
Checking exceptions: The most representative checking exceptions are those caused by user errors or problems that the programmer could not have foreseen. For example, when trying to open a nonexistent file, an exception occurs that cannot simply be ignored at compile time.
Runtime exceptions: Runtime exceptions are exceptions that can be avoided by programmers. In contrast to checking exceptions, runtime exceptions can be ignored at compile time.
Errors: Errors are not exceptions, but problems outside the programmer’s control. Errors are generally ignored in code. For example, when a stack overflow occurs, an error occurs that is not detected at compile time.
Note:
1. Checking exception: Compilation cannot pass without processing
2. Non-checking exceptions: compilation without handling can pass, if there is a throw directly to the console
3. Runtime exceptions: Non-checking exceptions
4. Non-runtime exceptions: Check exceptions
2.1 Hierarchy of Exception classes
All Exception classes are subclasses inherited from the java.lang.Exception class.
The Exception class is a subclass of Throwable. In addition to the Exception class, Throwable has a subclass Error.
Java programs generally do not catch errors. Errors typically occur during serious failures that are outside the scope of Java programs to handle.
Error is used to indicate errors in the runtime environment.
For example, the JVM runs out of memory. Generally, programs do not recover from errors.
Exception classes have two main subclasses: IOException and RuntimeException.
2.2 Built-in Java Exception Classes
Java built-in exception classes have most commonly used checking and non-checking exceptions. The Java language defines several exception classes in the java.lang standard package. A subclass of the standard runtime exception class is the most common exception class. Because the java.lang package is loaded into all Java programs by default, most exceptions inherited from runtime exception classes can be used directly.
2.3 Catching Exceptions
Use the try and catch keywords to catch exceptions. Try /catch blocks are placed where exceptions can occur.
The code in a try/catch block is called protected code, and the syntax for using try/catch is as follows:
try
{
// Program code
}catch(ExceptionName e1)
{
/ / Catch block
}
The Catch statement contains the declaration of the type of exception to Catch. When an exception occurs in the protected code block, the catch block after the try is checked.
If an exception occurs that is contained in a catch block, the exception is passed to that catch block, just as an argument is passed to a method.
2.4 Multiple capture blocks
A try block followed by multiple catch blocks is called multiple catch.
The syntax for multiple capture blocks looks like this:
try{
// Program code
}catch(exception type 1 exception variable name 1){
// Program code
}catch(exception type 2 exception variable name 2){
// Program code
}catch(exception type 2 exception variable name 2){
// Program code
}
The code snippet above contains three catch blocks.
You can add any number of catch blocks after a try statement.
If an exception occurs in the protected code, the exception is thrown to the first catch block.
If the data type of the exception thrown matches ExceptionType1, it will be caught here.
If it does not match, it is passed to the second catch block.
This is done until the exception is caught or passes all catch blocks.
2.5 Throws /throw keyword:
If a method does not catch a checking exception, the method must be declared using the THROWS keyword. Throws the keyword at the end of the method signature.
You can also use the throw keyword to throw an exception, whether it is newly instantiated or just caught.
The declaration of the following method throws a RemoteException:
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
A method can declare to throw multiple exceptions separated by commas.
2.6 Finally keyword
The finally keyword is used to create a block of code that executes after the try block.
Code ina finally code block is always executed whether or not an exception occurs.
In the finally code block, you can run statements of the cleanup nature, such as cleanup types.
Note the following:
A catch cannot exist independently of a try.
It is not mandatory to add a finally block after a try/catch.
You cannot have a try code without a catch block or a finally block.
No code can be added between try, catch, and finally blocks.
2.7 Declaring a Custom Exception
In Java you can customize exceptions. Here are a few things to keep in mind when writing your own exception classes.
All exceptions must be subclasses of Throwable.
If you want to write a checking Exception class, you need to inherit the Exception class.
If you want to write a run-time exception class, you need to extend the RuntimeException class.
You can define your own exception class as follows:
class MyException extends Exception{
.
}
Exception classes created by inheriting only the Exception class are checking Exception classes.
The instance
The following example is a simulation of a bank account, which is identified by the bank card number and can be used for deposit and withdrawal operations.
InsufficientFundsException. Java file code:
/ / file name InsufficientFundsException. Java
import java.io.*;
// A custom Exception class that inherits the Exception class
public class InsufficientFundsException extends Exception
{
// The amount used here is used to store money that is not available when an exception occurs
private double amount; // Privatized, obtained by getAmount()
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}
In order to show you how to use our custom exception class, in the following CheckingAccount class contains a withdraw () method throws an InsufficientFundsException anomalies.
Checkingaccount.java file code:
// The file name checkingAccount.java
import java.io.*;
// This type of simulated bank account
public class CheckingAccount
{
//balance is the balance and number is the card number
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
// Solution: Save money
public void deposit(double amount)
{
balance += amount;
}
// Method: Withdraw money
public void withdraw(double amount) throws
InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount – balance;
throw new InsufficientFundsException(needs);
}
}
// Method: return the balance
public double getBalance()
{
return balance;
}
// Method: return the card number
public int getNumber()
{
return number;
}
}
The BankDemo program below demonstrates how to call the deposit() and withdraw() methods of the CheckingAccount class.
Bankdemo.java file code:
// The file name is bankdemo.java
public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println(“Depositing $500…” );
C.d eposit (500.00);
try
{
System.out.println(“\nWithdrawing $100…” );
C.w ithdraw (100.00);
System.out.println(“\nWithdrawing $600…” );
C.w ithdraw (600.00);
}catch(InsufficientFundsException e)
{
System.out.println(“Sorry, but you are short $”
+ e.getAmount());
e.printStackTrace();
}
}
}
Compile the above three files and run the program BankDemo, resulting in something like this:
Depositing $500…
Withdrawing $100…
Withdrawing $600…
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
2.8 Common Exceptions
There are two types of exceptions and errors defined in Java.
JVM(Java Virtual Machine) exception: An exception or error thrown by the JVM. For example: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException class.
Program-level exception: An exception thrown by a program or API program. Examples include the IllegalArgumentException class and the IllegalStateException class.
2.9 Use exceptions according to the following principles:
1: When the current method is overridden, the overriding method must throw the same exception or a subclass of the exception.
2: Use a try-catch statement in the current method declaration to catch exceptions.
3: If the parent class throws more than one exception, the override method must throw a subset of those exceptions and cannot throw new ones.
2.10 Exception Summary:
Write the picture description here
As you can see, all exceptions and errors are inherited from the Throwable class, which means that all exceptions are one object.
Generally speaking, anomalies are divided into two parts:
1. Error – Error: refers to the error that cannot be handled by the program. It is a major error that occurs when the application is running. For example, outofMemoryErrors that occur when the JVM is running and port occupancy that occurs when Socket programming cannot be handled by the program.
2. Exception – Exception: Exceptions can be divided into runtime exceptions and compile exceptions
(1) Runtime exceptions: that is, RuntimeExceptions and their like. This type of exception is not detected by the compiler at the time of code writing. It may not need to be caught, but the programmer can also catch and throw it as needed. Common RUNtimeException has: NullpointException (null pointer exception), ClassCastException (abnormal) type conversion, IndexOutOfBoundsException abnormal (an array), etc.
(2) Compile exceptions: exceptions other than RuntimeException. The compiler prompts you to catch such exceptions at compile time. If you do not catch them, a compilation error occurs. Common compilation exceptions include: IOException (stream transmission exception), SQLException (database operation exception), etc.
3, Java processing exception mechanism: throw exceptions and catch exceptions, a method can catch exceptions, must be Java code somewhere thrown exceptions. Simply put, exceptions are always thrown first and then caught.
Throw throws:
public void test() throws Exception {
throw new Exception();
}
The above code clearly shows the difference between the two. Throws indicates that a method declaration may throw an Exception, and throws indicates that a defined Exception is thrown (either a custom inherited Exception or a Java Exception class).
5. Let’s see how to catch exceptions:
(1) First, Java uses a try — catch or try — catch — finally code block for exception catching. The program will catch the code inside the try code block. If an exception is caught, the catch code block will be processed. If there is a finally, the code in finally is executed after a catch. However, there are two problems:
A. Look at the following code:
try{
// Code to capture
}catch (Exception e) {
System.out.println(“catch is begin”);
Return 1;
}finally{
System.out.println(“finally is begin”);
}
In a catch there is a return. Will finally be executed? The answer is yes, the result of the above code is:
catch is begin
finally is begin
That is, catch code is executed first, finally code is executed, and then return1;
B. Look at the following code:
try{
// Code to capture
}catch (Exception e) {
System.out.println(“catch is begin”);
Return 1;
}finally{
System.out.println(“finally is begin”);
return 2 ;
}
In b, the output is the same as in A, but return 2 is returned; A return ina catch will not be executed because finally has already returned. That is, finally is always executed before a catch return. (This is a common interview question!)
6, for the Exception of the capture should not feel convenient and several exceptions combined with an Exception to capture, such as IO exceptions and SQL exceptions, so completely different two exceptions should be handled separately! And instead of a simple e.printStackTrace(), you should do detailed handling in a catch. For example, console to print details or log.
Note: The difference between exceptions and errors: exceptions can be handled by the program itself, and errors cannot be handled.
The Java language defines several exception classes in the java.lang standard package. A subclass of the standard runtime exception class is the most common exception class. Because the java.lang package is loaded into all Java programs by default, most exceptions inherited from runtime exception classes can be used directly.
Note: Finally may not be executed, e.g., system.exit (-1); Finally will not be executed
More technical information can be obtained from itheimaGZ