Java Fundamentals 18 Exception

Like you who love programming!
Learn SpringBoot actual combat course https://edu.csdn.net/course/detail/31433
Learn SpringCloud introductory course https://edu.csdn.net/course/detail/31451


Preface

In this article, let's understand the exception handling mechanism in Java.

What is abnormal

Errors that occur when the program is running, once an exception occurs, it must be handled, if the program is not handled, the execution will be interrupted

Exception architecture

Insert picture description here
Throwable is the parent class of exceptions and errors, which can be generated and thrown by the JVM.
Subclasses of Throwable:

  • Exception The
    program can be processed after the exception occurs, and the program can be executed normally after processing
  • Error errors
    are generally system-level errors, such as StackOverflow stack overflow and OutOfMemoryError memory overflow. After they occur, they cannot be processed, and the code can only be modified to avoid them.

Abnormal classification

  • Unchecked Exception
    RuntimeException and its subclasses, the program does not require processing
  • Checked Exception Checked Exception is
    not RuntimeException, and the program requires processing

Common exception

Class name abnormal
NullPointerException Null pointer exception
ClassCastException Type conversion exception
ArrayIndexOutOfBoundsException Array subscript out of bounds exception
StringIndexOutOfBoundsException String subscript out of bounds exception
NumberFormatException Number format is abnormal
InputMismatchException Input format is abnormal
IllegalArgumentException Wrong parameter exception
ArithmeticException Arithmetic exception
ParseException Date parsing exception
SQLException Database exception
IOException Input and output abnormal
ClassNotFoundException Class not found exception

try-catch exception handling

After the exception is handled, the program can run normally.
Syntax:

try{
	可能出现异常的代码
}catch(异常类型 ex){
	处理异常的代码
}

Exception handling process:

  • If there is an exception in the code in the try, the JVM will automatically throw an exception, the program jumps to the catch to perform exception handling, and the program executes normally after the processing ends.
  • If there is no exception in the try code, the try code is executed and the catch is skipped to execute the following code.

Common methods of exception
Exception method:

Method name effect
void printStackTrace() Print stack information
String getMessage() Get exception information
Throwable getCause() Get the upper level exception

Multiple catch exception handling

grammar:

try{
	可能出现异常的代码
}catch(异常类型1 ex){
	处理代码1;
}catch(异常类型2 ex){
	处理代码2;
}...

Exception handling process:

  • Once an exception occurs, match the exception with each catch block, if the match is successful, execute the catch and end
  • If it does not match, then determine the exception type of the next catch.
    Note: If there are other abnormal parent classes in the catch, the parent class exception must be placed last

try-catch-finally exception handling

Finally, the code in finally will be executed anyway
. There are some codes in the program that must be executed, such as: database connection closure, file stream closure, network connection closure

try{
	可能出现异常的代码
}catch(异常类型 ex){
	异常处理
}finally{
	如论如何都执行的代码
}

Exception handling process:

  • If there is an exception in the try, jump to the catch to perform processing, and finally execute the finally code;
  • If there is no exception in try, try is executed, and finally executes finally.

try-catch-finally case

Scanner input = new Scanner(System.in);
try{
	System.out.println("输入一个数:");
	int num1 = input.nextInt();
	System.out.println("输入一个数:");
	int num2 = input.nextInt();
	int result = num1 / num2;
	System.out.println("result = " + result);
}catch(ArithmeticException ex){
	System.out.println("出现了算术异常");
	ex.printStackTrace();
}catch(InputMismatchException ex){
	System.out.println("出现了输入格式异常");
	ex.printStackTrace();
}catch(Exception ex){
	ex.printStackTrace();
}finally{
	System.out.println("最终执行的代码");
}
System.out.println("程序执行完毕~~~");

throws and throw keywords

The throws keyword is
used to declare an exception in a method. Once the method declares an exception, the method does not need to handle the exception, and the method caller handles it.
Generally used for non-runtime exceptions.
grammar:

public 返回值类型 方法名(参数列表) throws 异常类型1, 异常类型2...{

}

The throw keyword is
used to manually throw exceptions and prompt the caller.
Syntax:

if(条件){
	throw new 异常类型("异常描述信息");
}

Exercise: Enter the age of a person. The age must be between 0 and 100. If it exceeds, an IllegalArgumentException will be thrown.

/**
 * 输入年龄
 * @throws IllegalArgumentException
 */
static void inputAge() throws IllegalArgumentException{
	Scanner input = new Scanner(System.in);
	System.out.println("输入年龄(0~100)");
	int age = input.nextInt();
	//手动抛出异常
	if(age < 0 || age > 100){
		throw new IllegalArgumentException("年龄必须在0到100之间");
	}
	System.out.println("年龄是"+age);
}

public static void main(String[] args) {
	try{
		inputAge();
	}catch(IllegalArgumentException ex){
		ex.printStackTrace();
	}
}

Custom exception

Under certain specific business requirements, exceptions in the system cannot be handled well or represent business problems. You can customize exception classes to solve specific business problems.
For example, when withdrawing money from a bank account, it is necessary to judge whether the balance is sufficient.
Implementation steps:
1) Define the class to inherit Exception or its subclasses.
2) When certain conditions are met, use throw in the method to throw an exception
3) When declaring the method, use throws statement exception
4) When calling the method, use try-catch to handle the exception

/**
 * 余额不足异常
 * @author xray
 *
 */
public class BalanceException extends Exception{

	public BalanceException(String msg){
		//将异常描述信息传给父类
		super(msg);
	}
}
/**
 * 银行账户类
 * @author xray
 *
 */
public class BankAccount {

	private String name;
	private int balance;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getBalance() {
		return balance;
	}
	public void setBalance(int balance) {
		this.balance = balance;
	}
	public BankAccount(String name, int balance) {
		super();
		this.name = name;
		this.balance = balance;
	}
	public BankAccount() {
		super();
	}
	/**
	 * 存钱
	 * @param money
	 */
	public void saveMoney(int money){
		this.balance += money;
		System.out.println("账户"+name+"的余额是"+balance);
	}
	/**
	 * 取钱
	 * @param money
	 * @throws BalanceException 
	 */
	public void takeMoney(int money) throws BalanceException{
		//如果余额不足,就抛出自定义异常
		if(balance < money){
			throw new BalanceException("对不起,您账户余额不足");
		}
		this.balance -= money;
		System.out.println("账户"+name+"的余额是"+balance);
	}
}
public class TestBank {

	@Test
	public void testBankAccount(){
		//创建银行账户
		BankAccount account = new BankAccount("恒哥",10000);
		account.saveMoney(1000);
		//处理异常
		try {
			account.takeMoney(10000);
		} catch (BalanceException e) {
			e.printStackTrace();
		}
	}
}

End

Assignment:
Define student class, define name, age, gender attributes and learning method
Define a method, enter name, age, gender in the method to create a student object
gender input error, RuntimeException will be thrown, and contain information: gender must be male Or female If the
age is entered incorrectly, RuntimeException will be thrown and contain information: the age must be between 18 and 30.
Use throws to declare RuntimeException in the
method. When calling the method, use try-catch to handle the exception.


If you need to learn other Java knowledge, poke here ultra-detailed knowledge of Java Summary

Guess you like

Origin blog.csdn.net/u013343114/article/details/112676142