Notes on Java exception handling mechanism

What is an exception

Abnormal situation
An abnormal condition that occurs during the operation of a program, resulting in the unexpected termination of the program.

How to handle exceptions

In Java, the exception information is encapsulated into a class. When a problem occurs, it will create an exception class object and throw exception related information (such as the location and reason of the exception)

1. In case of exception, check the code, modify the code and solve the exception
2. Solve the possible exceptions in the code through if judgment. The code structure is bloated, which is not conducive to reading and maintenance
3. Throwable class (super class of all errors and exceptions in Java language)
**Error: * * an error has occurred. You can only modify the code and cannot use the exception handling mechanism to solve it
exception: checked exception / compilation exception: an exception that occurs during the writing of a java program. The code will have a red wavy line
Non checked exception / runtimeException: run-time exception, an exception that occurs during the running of a java program
Summary: runtimeException and its subclasses are run exceptions, while others are compilation exceptions

What are the common exception handling mechanisms

  • The jvm has a set of exception handling by default
    The processing method of the JVM can only print out exception information, not personalized operation
    How does the JVM handle exceptions

    Summary: when the JVM handles exceptions, the code after the exception will not be executed

  • Use try catch: exception capture (shortcut key alt+shift+R+z)

//Code that may cause exceptions
}catch(Exception type variable name){//Exception e
//Code to handle exceptions
//e.getMessage(); Print exception information
//e.printStackTrace(); Print the stack information of the exception: what exception, exception constant

  • Multiple catch
//Possible exception codes
}catch(Exception type 1 variable name 1){
//Handling exceptions
}catch(Exception type 2 variable name 2){
//Handling exceptions
}catch(Exception type 3 variable name 3){
//Handling exceptions

Features: 1. catch is in order. The matching of subclasses is performed first, and then the matching of parent classes
2. catch can only execute one at a time
3. Multiple catch variable names with the same name do not affect

  • try-catch-finally
    Finally: the content in finally will be output regardless of whether an exception occurs in the try catch
    Application scenario: IO flow: on / off; Operation of connecting data: open / close connection
//Possible exception codes
}catch(Exception type 1 variable name 1){
//Handling exceptions
}catch(Exception type 2 variable name 2){
//Handling exceptions
}catch(Exception type 3 variable name 3){
//Handling exceptions
//It will be executed whether there are exceptions or not

1. If the code in try returns, if the program executes normally, execute the code before return first, and then execute the code in finally
2. If an exception occurs to the code in try, execute the code in catch first, then the code in finally, and then end the program. The code behind the exception is not executed.
3. finally, exit after encountering the forced end of the program (System.exit(0);) It won't happen.
Note: return must be the last execution. The only case where fianlly does not execute: system exit(0);

  • Declare exception throws
    Definition: tells the caller of a method that an exception may occur in the method, but the exception is declared and not handled. Remind the caller of the need to handle exceptions.
//The declared exception must be written after the method ()
Access modifier return value type method name (formal parameter list) throws Exception type{};

After declaring an exception, you can handle it in two ways:
1. Catch exceptions using try catch
2. Continue to throw and leave it to the jvm for processing
How to declare exceptions:
1. throws + compile time exception: the exception must be handled, otherwise the program will report an error
2. throws + runtime exception: the caller can handle it or not

  • How to classify all exceptions of Exception
    Common exceptions at runtime

    Common compile exceptions

    **Note: * * if there is a red wavy line in the method when calling the method, and there is no problem with parameter passing and method name, it must be a compilation exception
  • throw exception
    Written in the method, it indicates that an exception must have occurred. Throw the exception and let the caller handle the exception.
    Syntax: throw new exception type (exception prompt information);
  • What's the difference between throw and throws
    1. Different definitions: throw exception object / throw exception type
    2. The definition locations are different: in the throw method body, / throws is behind the method list
    3. Different functions: throw throw throw exception / throws declare exception, which may or may not be
package com.m.demo;

public class Person {
	private String name;
	private int age;
	private char sex;
	public String getName() {
		return name;
	public void setName(String name) { = name;
	public int getAge() {
		return age;
	public void setAge(int age) throws Exception {
		if(age>=16&&age<=32) {
			this.age = age;
		}else {
			throw new Exception("Content out of range");
	public char getSex() {
		return sex;
	public void setSex(char sex) throws Exception {
		if(sex=='male'||sex=='female') { = sex;
		}else {
			throw new Exception("Wrong input");

class demo{
	public static void main(String[] args)  {
		Person p=new Person();
		try {
		} catch (Exception e) {

The difference between forced exit and return

Forced exit will not execute the code in finally. return will execute

Exception method override

1. If the parent class defines an exception, the child class can be defined, partially defined, or undefined
2. If the parent class does not throw exceptions, the child class cannot throw exceptions
3. The range of exceptions thrown by the subclass cannot be wider than that of the parent class

Custom exception

public class Custom exception class name extends Exception/  ...{
public Custom exception class name(){
public Custom exception class name(String s){
super(String s);

Log4j log usage

  1. Import the jar package of Log4j
  2. Create log4j configuration file: log4j properties
  3. Create log4j object (apache)
Logger logger=Logger.getLogger(Test.class);

Keywords: Java Back-end

Added by jthomp7 on Mon, 07 Mar 2022 07:39:26 +0200