Java se Basics - exception handling

1. Exception handling and exception overview

  • Exception: in the Java language, abnormal conditions during program execution are called "exceptions". (syntax and logic errors in the development process are not exceptions).
  • The abnormal events that occur during the execution of Java programs can be divided into two categories:

1.Error:

  • Serious problems that cannot be solved by the Java virtual machine. Such as: JVM system internal error, resource exhaustion and other serious situations. For example, StackOverflowError and OOM. Generally, targeted code is not written for processing.

2.Exception:

  • Other general problems caused by programming errors or accidental external factors can be handled with targeted code.
    For example:
     null pointer access
     trying to read a file that does not exist
     network connection interruption
     array subscript out of range
    The subclass of Exception can be divided into compile time Exception (checked) and run-time Exception (unchecked,RuntimeException)

There are generally two solutions to these errors:

  • One is to terminate the program in case of an error.
  • Another method is that programmers consider error detection, error message prompt and error handling when writing programs.

 the best way to catch errors is during compilation, but some errors only occur at run time.
For example, if the divisor is 0, the subscript of the array is out of bounds, etc
 classification:
Compile time and run time exceptions

2. Compile time exception

Compile time exception:

  • An exception that the compiler requires to be handled. That is, the general exception caused by external factors when the program is running. The compiler requires that Java programs must catch or declare all compile time exceptions.
  • For this kind of exception, if the program does not handle it, it may bring unexpected results.

Exception architecture:
java.lang.Throwable (parent class)
java.lang.Error: generally, targeted code is not written for processing.
java.lang.Exception: you can handle exceptions

Compile time exception (checked)

  • IOException
  • FileNotFoundException
  • ClassNotFoundException

3. Abnormal operation

Runtime exception:

  • An exception that the compiler does not require forced handling. It generally refers to the logic error in programming, which is an exception that programmers should actively avoid. The java.lang.RuntimeException class and its subclasses are runtime exceptions.
  • This kind of exception can not be handled because it is very common. If it is fully handled, it may affect the readability and running efficiency of the program.

Runtime exception (unchecked,RuntimeException)

  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • ClassCastException
  • NumberFormatException
  • InputMismatchException
  • ArithmeticException

4. Common exception example code

public class ExceptionTest {
	
	//******************The following are compile time exceptions***************************
	@Test
	public void test7(){
//		File file = new File("hello.txt");
//		FileInputStream fis = new FileInputStream(file);
//		
//		int data = fis.read();
//		while(data != -1){
//			System.out.print((char)data);
//			data = fis.read();
//		}
//		
//		fis.close();
		
	}
	
	//******************The following are runtime exceptions***************************
	//ArithmeticException
	@Test
	public void test6(){
		int a = 10;
		int b = 0;
		System.out.println(a / b);
	}
	
	//InputMismatchException
	@Test
	public void test5(){
		Scanner scanner = new Scanner(System.in);
		int score = scanner.nextInt();
		System.out.println(score);
		
		scanner.close();
	}
	
	//NumberFormatException
	@Test
	public void test4(){
		
		String str = "123";
		str = "abc";
		int num = Integer.parseInt(str);
		
		
		
	}
	
	//ClassCastException
	@Test
	public void test3(){
		Object obj = new Date();
		String str = (String)obj;
	}
	
	//IndexOutOfBoundsException
	@Test
	public void test2(){
		//ArrayIndexOutOfBoundsException
//		int[] arr = new int[10];
//		System.out.println(arr[10]);
		//StringIndexOutOfBoundsException
		String str = "abc";
		System.out.println(str.charAt(3));
	}
	
	//NullPointerException
	@Test
	public void test1(){
		
//		int[] arr = null;
//		System.out.println(arr[3]);
		
		String str = "abc";
		str = null;
		System.out.println(str.charAt(0));
		
	}
	
	
}

5. Exception handling method 1 (try catch finally)

When writing a program, it is often necessary to add detection code where errors may occur. For example, when performing x/y operation, it is necessary to detect that the denominator is 0, the data is empty, and the input is not data but characters. Too many if else branches will lead to the code lengthening, bloated and poor readability of the program. Therefore, the exception handling mechanism is adopted.

Java exception handling
The exception handling mechanism adopted by Java is to concentrate the exception handling program code together and separate it from the normal program code, making the program concise, elegant and easy to maintain.

Java exception handling method:

  • Method 1: try catch finally
  • Mode 2: throws + exception type

Method 1: try catch finally

  • Java provides a catch and throw model for exception handling.
  • If an exception occurs during the execution of a Java program, an exception class object will be generated
    The exception object will be submitted to the Java runtime system. This process is called throw ing an exception.
  • Generation of exception objects
  • Automatically generated by virtual machine:
    When the program is running, the virtual machine detects a problem with the program. If the corresponding handler is not found in the current code, it will automatically create an instance object of the corresponding exception class in the background and throw it automatically.
  • Manually created by developers
    Exception exception = new ClassCastException(); Creating a good exception object without throwing has no impact on the program, just like creating an ordinary object.
  • If an exception is thrown within a method, the exception object will be thrown to the caller's method for processing. If the exception is not handled in the caller method, it continues to be thrown to the call
    Method. This process will continue until the exception is handled. This process is called catch exception.
  • If an exception returns to the main() method and main() does not handle it, the program runs
    Line termination.
  • Programmers usually can only deal with exceptions and can't do anything about errors.

5.1 try catch finally instructions

  • Try catch finally syntax structure:
Exception handling is through
try catch finally Statement.
try{
......
Code that may cause exceptions
}catch(ExceptionName1 e){
......
When produced ExceptionName1 Handling measures in case of type I abnormality
}
catch(ExceptionName2 e){
......
When produced ExceptionName2 Handling measures in case of type I abnormality
}finally{
......
A statement that executes unconditionally whether an exception occurs or not
}
  • instructions:
  • 1.finally is optional.
  • 2. Use try to wrap the possible exception code. During execution, once an exception occurs, an object corresponding to the exception class will be generated. According to the type of this object, it will be matched in catch
  • 3. Once the exception object in the try matches a catch, it will enter the catch to handle the exception. Once the processing is completed, it jumps out of the current try catch structure (without writing finally). Continue with the following code
  • 4. If the exception type in catch has no child parent relationship, it doesn't matter who declares it on the top and who declares it on the bottom.
  • If the exception type in catch satisfies the child parent relationship, the child class must be declared on the parent class. Otherwise, an error is reported
  • 5. Common exception object handling methods:
  • ① String getMessage() ② printStackTrace()
  • 6. Variables declared in the try structure cannot be called after the try structure is created
  • 7. Try catch finally structure can be nested
  • Experience 1: use try catch finally to handle compile time exceptions, so that the program will no longer report errors at compile time, but errors may still be reported at run time. It is equivalent to using try catch finally to delay an exception that may occur during compilation until it occurs at run time.
  • Experience 2: in development, since runtime exceptions are common, we usually don't write try catch finally for runtime exceptions. For compile time exceptions, we say we must consider exception handling.

5.2 try catch finally example code

public class ExceptionTest1 {
	
	
	@Test
	public void test2(){
		try{
			File file = new File("hello.txt");
			FileInputStream fis = new FileInputStream(file);
			
			int data = fis.read();
			while(data != -1){
				System.out.print((char)data);
				data = fis.read();
			}
			
			fis.close();
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	@Test
	public void test1(){
		
		String str = "123";
		str = "abc";
		int num = 0;
		try{
			num = Integer.parseInt(str);
			
			System.out.println("hello-----1");
		}catch(NumberFormatException e){
//			System.out.println("numerical conversion exception occurs, don't worry...);
			//String getMessage():
//			System.out.println(e.getMessage());
			//printStackTrace():
			e.printStackTrace();
		}catch(NullPointerException e){
			System.out.println("There is a null pointer exception. Don't worry....");
		}catch(Exception e){
			System.out.println("There's something unusual. Don't worry....");
			
		}
		System.out.println(num);
		
		System.out.println("hello-----2");
	}
	
}
try-catch-finally in finally Use of:
 * 1.finally Is optional
 * 2.finally What is declared in is the code that must be executed. even if catch Another exception occurred in the, try There are return sentence, catch There are return Statements, etc.
 * 3.Like database connection, I / O flow, network programming Socket And other resources, JVM It cannot be recycled automatically. We need to release resources manually. The resource release at this time needs to be declared in finally in

6. Exception handling method 2 (throws + exception type)

  • Declaring to throw an exception is the second way to handle exceptions in Java
  • If an exception may be generated during the execution of a statement in a method, but it is not sure how to handle this exception, the method should explicitly declare that throwing an exception indicates that the method will not handle these exceptions, but the caller of the method is responsible for handling them.
  • In the method declaration, use the throws statement to declare the list of exceptions thrown. The exception type after throws can be
  • Therefore, the exception type generated in the method can also be its parent class.
  • Example of exception thrown by declaration:
public void readFile (String file) throws FileNotFoundException
......
//The operation of reading a file may result in an exception of type FileNotFoundException
FileInputStream fis new FileInputStream (file);
...
}

be careful:

  • 1."throws + exception type" is written at the declaration of the method. Indicates the type of exception that may be thrown when this method is executed. Once an exception occurs during the execution of the method body, an exception class object will still be generated at the exception code. When this object meets the throw exception type, it will be thrown. Exception code and subsequent code will not be executed!
  • 2. Experience: try catch finally: the exception is really handled.
  • Throws simply throws the exception to the caller of the method. The exception is not really handled.
  • 3. How to choose whether to use try catch finally or throws in development?
    If the overridden method in the parent class does not handle exceptions in the throw mode, the overridden method of the child class cannot use throws, which means that if there are exceptions in the overridden method of the child class, it must be handled in the try catch finally mode.
  • In the executed method a, several other methods are called successively, which are executed in a progressive relationship. We suggest that these methods be handled in the way of throws. For the executed method a, try catch finally can be considered.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;


public class ExceptionTest2 {
	
	
	public static void main(String[] args){
		try{
			method2();
			
		}catch(IOException e){
			e.printStackTrace();
		}
		
//		method3();
		
	}
	
	
	public static void method3(){
		try {
			method2();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	public static void method2() throws IOException{
		method1();
	}
	
	
	public static void method1() throws FileNotFoundException,IOException{
		File file = new File("hello1.txt");
		FileInputStream fis = new FileInputStream(file);
		
		int data = fis.read();
		while(data != -1){
			System.out.print((char)data);
			data = fis.read();
		}
		
		fis.close();
		
		System.out.println("hahaha!");
	}
	
	
}

7. Override the rule that the method throws an exception

  • An overridden method cannot throw an exception type that is more extensive than the overridden method.

Example code:

import java.io.FileNotFoundException;
import java.io.IOException;

/*
 * One of the rules for method overrides:
 * The exception type thrown by the method overridden by the subclass is not greater than the exception type thrown by the method overridden by the parent class
 * 
 * 
 */
public class OverrideTest {
	
	public static void main(String[] args) {
		OverrideTest test = new OverrideTest();
		test.display(new SubClass());
	}

	
	public void display(SuperClass s){
		try {
			s.method();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

class SuperClass{
	
	public void method() throws IOException{
		
	}
	
	
}

class SubClass extends SuperClass{
	public void method()throws FileNotFoundException{
		
	}
}

8. Throw an exception manually

  • Java exception class objects are automatically generated and thrown by the system when exceptions occur during program execution. They can also be manually created and thrown as needed.
  • First, the exception class object is generated, and then the throw statement is used to realize the throw operation and submit it to the Java runtime environment.
IOException e new IOException();
	throw e;
  • The exception that can be thrown must be an instance of Throwable or its subclass. The following statement will produce syntax errors during compilation:
throw new String("want to throw");

Note:

The difference between throw and throws: throw is the way to generate an exception object, which is declared in the method body.
throws is a way to handle exceptions, which is declared at the declaration of the method.

9. User defined exception class

  • Generally, user-defined exception classes are subclasses of RuntimeException.
  • Custom exception classes usually require writing several overloaded constructors.
  • A serialVersionUID is required for custom exceptions
  • Custom exceptions are thrown through throw.
  • The most important part of a custom exception is the name of the exception class. When an exception occurs, you can
    The name determines the exception type.
/*
 * How to customize exception classes?
 * 1. Inherited from the existing Exception structure: RuntimeException, Exception
 * 2. Provide global constant: serialVersionUID
 * 3. Provides overloaded constructors
 * 
 */
public class MyException extends Exception{
	
	static final long serialVersionUID = -7034897193246939L;
	
	public MyException(){
		
	}
	
	public MyException(String msg){
		super(msg);
	}
}

Example code:

public class StudentTest {
	
	public static void main(String[] args) {
		try {
			Student s = new Student();
			s.regist(-1001);
			System.out.println(s);
		} catch (Exception e) {
//			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}
	
}


class Student{
	
	private int id;
	
	public void regist(int id) throws Exception {
		if(id > 0){
			this.id = id;
		}else{
//			System.out.println("the data you entered is illegal!");
			//Manually throw exception object
//			throw new RuntimeException("the data you entered is illegal!");
//			throw new Exception("the data you entered is illegal!");
			throw new MyException("You cannot enter a negative number");
			//FALSE
//			throw new String("negative number cannot be entered");
		}
		
	}

	@Override
	public String toString() {
		return "Student [id=" + id + "]";
	}
	
	
}

Tags: Java

Posted on Tue, 23 Nov 2021 03:03:42 -0500 by johnska7