[Java study notes] IO flow exception

table of Contents

1. Definition of exception

2. The classification of anomalies

2.1 Error

2.2 Exception

3. Exception handling method

3.1 JVM's default processing scheme 

3.2 try...catch to handle exceptions

 3.3 Handle exceptions by throws 

4. The difference between throw and throws

5. The difference between final, finally and finalize

6. Custom exception


1. Definition of exception

An exception is an abnormal situation in the running process of the Java program.

2. The classification of anomalies

As can be seen from the above figure, there are two types of abnormalities:

2.1 Error

This kind of problem is generally very serious, we will not deal with it! For example: memory overflow

2.2 Exception

  • Runtime exceptions: RuntimeException and its subclasses are runtime exceptions. This kind of exception does not need to be handled, and the compilation will pass. When encountering this kind of exception, you need to modify the code!
  • Compile-time exception: Except for RuntimeException and its subclasses, all other subclasses in Exception are compile-time exceptions. This kind of exception must be handled, otherwise the compilation will not pass!

3. Exception handling method

3.1 JVM's default processing scheme 

Let's first look at a piece of code:

package com.hw.exception;

public class ExceptionDemo1 {
	public static void main(String[] args) {
		method1();
	}

	private static void method1() {
		int a = 10;
		int b = 0;
		System.out.println(a/b);
		System.out.println("==========end==========");
	}
}

ArithmeticException appears after running , as shown below, you can see that the statement after the exception is not output on the console! 

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at com.hw.exception.ExceptionDemo1.method1(ExceptionDemo1.java:11)
	at com.hw.exception.ExceptionDemo1.main(ExceptionDemo1.java:5)

JVM found that the operation violated the rules of mathematical operation. Java described this common problem and encapsulated it into an object called ArithmeticException. When the division by zero operation occurs, the JVM packages the problem into an exception object, and throws the object to the caller main function, new ArithmeticException("/by zero");

When the main function receives this problem, there are two ways to deal with it:

  • Solve the problem yourself, and then continue to run
  • I don’t have a specific processing method. I only have to hand it over to the JVM that calls main . The JVM has a default exception handling mechanism to handle the exception, and print the name of the exception, the exception information, and the location where the exception occurs On the console, stop the program at the same time!

The above code uses the JVM's default processing scheme!

Let's take a look at how to use try..catch and throws to handle exceptions!

3.2 try...catch to handle exceptions

try {
    可能出现问题的代码;
}catch(异常名 变量) {
    针对问题的处理;
}finally {
    释放资源;
}

注意:
    try里面的代码越少越好;
    catch里面必须有内容;

Use try...catch to process the code in 3.1 above, as shown below:

public static void main(String[] args) {
		// method1();
		method2();
}

private static void method2() {
	int a = 10;
	int b = 0;
	try {
		System.out.println(a/b);
	} catch (ArithmeticException e) {
		e.printStackTrace();
	}
	System.out.println("==========end==========");
}

The results of the operation are as follows:

java.lang.ArithmeticException: / by zero
	at com.hw.exception.ExceptionDemo1.method2(ExceptionDemo1.java:13)
	at com.hw.exception.ExceptionDemo1.main(ExceptionDemo1.java:6)
==========end==========

 3.3 Handle exceptions by throws 

Use throws to process the code in 3.1 above, as follows:

// 尽量不要在main方法上throws抛出异常
public static void main(String[] args) {
	// method1();
	// method2();
	try {
		method3();
	} catch (ArithmeticException e) {
		e.printStackTrace();
	}

	System.out.println("==========end==========");
}

private static void method3() throws ArithmeticException {
	int a = 10;
	int b = 0;
	System.out.println(a/b);
}

The results of the operation are as follows: 

java.lang.ArithmeticException: / by zero
	at com.hw.exception.ExceptionDemo1.method2(ExceptionDemo1.java:13)
	at com.hw.exception.ExceptionDemo1.main(ExceptionDemo1.java:6)
==========end==========

4. The difference between throw and throws

throws

  • Used after the method declaration, followed by the exception class name
  • Can be followed by multiple exception class names, separated by commas
  • Indicates that an exception is thrown, which is handled by the caller of the method
  • Throws represents the possibility of exceptions, and these exceptions do not necessarily occur

throw

  • Used in the method body, followed by the abnormal object name
  • Only one exception object name can be thrown
  • Indicates that an exception is thrown, handled by the statement in the method body
  • Throw is an exception, and execution of throw must throw some kind of exception

Requirements: Demonstrate the throwing of exception objects at compile time and exception objects at runtime respectively!

4.1 Throwing of an exception object at runtime, the code is as follows:

public static void main(String[] args) {
	method1();
}

// 演示运行时异常对象的抛出
private static void method1() {
	int a = 10;
	int b = 0;
	if (b == 0) {
		throw new ArithmeticException("除数为0!");
	} else {
		System.out.println(a / b);
	}
}

4.2 The throwing of the exception object at compile time is as follows:

 

5. The difference between final, finally and finalize

final: The final meaning, you can modify the class, member variables, member methods;

  • Modified class, the class cannot be inherited;
  • Modified variables, variables are constants;
  • Modification method, method cannot be overridden.

finally: is a part of exception handling, used to release resources. Generally speaking, the code will definitely be executed, special case: the JVM exits before the execution reaches finally!

finalize: is a method of the Object class, used for garbage collection!

6. Custom exception

It is impossible for Java to consider all situations, so in actual development, we may need to define exceptions ourselves. And if we write a class at will, it cannot be regarded as an exception class. If you want your class to be an exception class, you must inherit from Exception or RuntimeException.

Requirements: Custom exceptions, the test score must be between 0-100!

Customize an exception class MyException.java, the code is as follows:

package com.hxs.exception;

/**
 * 自定义异常类
 * 
 * @author HW
 * 
 */
public class MyException extends Exception {

	public MyException() {
	}

	public MyException(String message) {
		super(message);
	}

	public MyException(Throwable cause) {
		super(cause);
	}

	public MyException(String message, Throwable cause) {
		super(message, cause);
	}
}

Teacher.java code is as follows:

package com.hxs.exception;

public class Teacher {
	public void check(int score) throws MyException {
		if(score < 0 || score > 100) {
			throw new MyException("输入的学生分数必须在0-100之间!");
		} else {
			System.out.println("输入的学生分数没有问题!");
		}
	}
}

The custom exception test class TeacherTest.java code is as follows:

package com.hxs.exception;

import java.util.Scanner;

/**
 * 自定义异常测试类
 * 
 * @author HW
 * 
 */
public class TeacherTest {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入学生的成绩:");
		int score = sc.nextInt();
		
		Teacher teacher = new Teacher();
		try {
			teacher.check(score);
		} catch (MyException e) {
			e.printStackTrace();
		}
	}
}

For example, if you enter a score greater than 100, a custom exception will be thrown, as follows:

Guess you like

Origin blog.csdn.net/weixin_44679832/article/details/105366037