java based exception handling (detailed notes)

catalogue

Exception overview

Examples of common exceptions

Null pointer exception NullPointerException

Array subscript out of bounds exception ArrayIndexOutOfBoundsException

Exception throwing and catching

Throw exception

Catch exception

Throw an exception in a method

Throw an exception using the throws keyword

Throw an exception using the throw keyword (custom exception)

Principle of using exceptions

 

Exception overview

In Java, some errors that may occur when the program runs are called exceptions. An exception is an event that occurs during program execution. It interrupts the normal instruction flow of the destination being executed.  

Video notes:

Exception encountered during Java program execution:

  • java.lang.Error: generally, targeted code is not written for processing
  • Java.lang.Exception: exception handling is allowed
  • Compile time exception (checked) and run time exception (unchecked)

1. Error: a serious problem that cannot be solved by the Java virtual machine. For example: JVM system internal error

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 nonexistent file, network connection interruption, array subscript out of bounds

Let's look at the most common time to divide 0

public class test {
	public static void main(String[] args)
	{
	int a=3/0;
	System.out.println(a);
}
}

The result of the program running reports that an arithmetic exception ArithmeticException has occurred. The system is not executing and ends in advance. This situation is called anomaly.

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

Stack overflow (call main (args) in main)

public class test {
	public static void main(String[] args)
	{
	Integer [] a=new Integer[1024*1024*1024];
}
}

Heap overflow (OutOfMemoryError)

Book content:

Java language is an object-oriented programming language, so exceptions also appear as instances of classes in the Java language. When a method makes an error, the method will create an object and pass it to the running system. This object is the exception object. Through the exception handling mechanism, the handling code under abnormal conditions can be separated from the main logic of the program, that is, handling exceptions in other places while writing the main process of the code.  

Examples of common exceptions

Null pointer exception NullPointerException

public class test {
	public static void main(String[] args)
	{
	int a[]=null;
	System.out.println(a[5]);
}
}

Array subscript out of bounds exception ArrayIndexOutOfBoundsException

public class test {
	public static void main(String[] args)
	{
	int a[]=new int[5];
	System.out.println(a[5]);
}
}

Exception throwing and catching

In order to ensure the effective execution of the program, the thrown exceptions need to be handled accordingly. In Java, if a method throws an exception, you can either catch the exception in the current method and then handle the exception, or throw the exception up and let the method caller handle it.

Throw exception

After the exception is thrown, if nothing is done, the program will be terminated.

For example, converting a string to an Integer can be implemented through the parseInt() method of the Integer class. However, if the string is not in numeric form, the parseInt() method will throw an exception, and the program will terminate where the exception occurs, instead of executing the following statement

public class test {
	public static void main(String[] args)
	{
String str="abc";
System.out.println(str);
int a=Integer.parseInt("20L");
System.out.println(a);
}
}

The NumberFormatException exception, abc and output are just the problems of the following statements, resulting in code termination

An exception is thrown and the subsequent code is not executed

Catch exception

The exception capture structure of Java language consists of try, catch and finally. Among them, the try statement block stores Java statements that may have exceptions; The catch statement block is used to trigger the caught exception after the try statement block; The final statement block is the last execution part of the exception structure. No matter how the code in the try statement block exits, the finally statement block will be executed

try{
//Code block
}
catch(exception1 e)//(exception type, variable name)
{
//Processing of exception1
}
catch(exception2 e)//(exception type, variable name)
{
//Processing of exception2
}
finally{
//Code block (code that must be executed)
}

Template as above

public class test {
	public static void main(String[] args)
	{
String str="abc";
System.out.println(str);
try {
int a=Integer.parseInt(str);
System.out.println("Guess what");
		}
		catch(Exception e)
		{
			System.out.println("Something's wrong. Don't panic");
		}
		System.out.println("You see, they say it's not a problem");
}
}

Use e.printStackTrace(); Statement is obtained after outputting the exception nature

 

Video notes:

  • finally is optional
  • try is used 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, match it in catch - for example, the Exception e in our above code is written as NumberFormatException e, which corresponds to it
  • Once the exception object in the try matches a catch, it enters the catch for exception handling. Once the processing is completed, it will jump out of the current try catch structure (if there is no finally at this time). Continue with the following code
  • If the exception type in catch satisfies the child parent relationship, the child class must be declared on the parent class.
  • Variables declared in the try structure cannot be called after the try structure
  • When using this structure to handle exceptions, there is no error at compile time, but it is still possible to report an error at run time, which is equivalent to prolonging the exception until it occurs at run time; In development, because runtime exceptions are common, we usually do not write try catch finally for runtime exceptions

finally statement block

In the following four special cases, finally blocks will not be executed:

  1. An exception occurred in a finally statement block
  2. In the previous code, system. Net was used Exit() exits the program
  3. The thread on which the program is located dies
  4. Turn off the CPU

 

 

By comparison, it is found that the second figure does not write finally, but does not affect the embodiment of the result

  • finally is optional
  • finally, the code declared is bound to be executed. Even if an exception occurs in catch, there is a return statement in try and a return statement in catch

Throw an exception in a method

Throw an exception using the throws keyword

The throws keyword is usually used when declaring a method to specify the exceptions that the method may throw. Multiple exceptions can be separated by commas.

public class test {
	static void p()throws NegativeArraySizeException{
		//Define a method and throw a NegativeArraySizeException
		int[] a=new int[-4];
	}

	public static void main(String[] args)
	{

		try {
			p();
		 }
	catch(NegativeArraySizeException e) {
		System.out.println("p()Method");
	  }
	
}
	}

Note: if it is an Error class, RuntimeException class or their subclasses, you can declare the exception to be thrown without using the throws keyword. The compilation can still pass smoothly, but it will be thrown by the system at run time.  ""

"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

Throw an exception using the throw keyword (custom exception)

The throw keyword is usually used in the method body and throws an exception object. The program terminates immediately when the throw statement is executed, and the statements after it are not executed. After throwing an exception, if you want to catch and handle the exception in the upper level code, you need to use the throws keyword in the method throwing the exception, and specify the exception to be thrown in the method declaration; If you want to catch the exception thrown by throw, you must use the try catch statement block

public class test extends Exception {
	String name;
	public test(String errorname)
	{
		name=errorname;
	}
	public String getName()
	{
		return name;
	}		
}
public class captor{
	static int q(int x,int y)throws test{
		if(y<0)
		{
			throw new test("Divisor cannot be negative");
		}
		return x/y;
	}
	public static void main(String[] args)
	{
try {
	int result=q(3,-1);
}catch(test e) {
	System.out.println(e.getName());
}catch(ArithmeticException e)
{
	System.out.println("Divisor cannot be 0");
}catch(Exception e)
{
	System.out.println("Other exceptions occurred");
}
}
}

Principle of using exceptions

Java exceptions force users to consider the robustness and security of the program. Exception handling should not be used to control the normal process of the program. Its main function is to capture the exceptions that occur when the program is running and deal with them accordingly. When writing code to handle possible exceptions of a method, you can follow the following principles:

  • Use the try catch statement in the current method declaration to catch exceptions
  • When a method is overridden, the method overriding it must throw the same exception or subclass of the exception
  • If the parent class throws multiple exceptions, the override method must throw a subset of those exceptions and cannot throw new exceptions

Learning is like sailing against the current. If you don't advance, you will fall back. These days, because your old watch is busy getting married, you can only take time to take notes. Work hard with Xiao Wu!

 

Keywords: Java Back-end JavaSE

Added by thunderbox on Mon, 10 Jan 2022 17:52:46 +0200