Error handling mechanism in javase Java

Posted by nihal on Wed, 09 Feb 2022 14:36:26 +0100

Basic exception handling syntax and procedures

The error handling mechanism in Java refers to non compiled errors, that is, non syntax errors. Similar to the division by zero error, that is, you can't divide by 0 during division. Java will encounter the following errors: example: system out. println(16 / 0);

The ArithmeticException here is the inner exception class of Java, and the exception name is "by zero" after the colon.

The above error handling method is to throw an exception, and another method is to grab an exception (try...catch). And we can define the handling of such errors by ourselves:

        int m;
		int n;
		
		Scanner in = new Scanner(System.in);
		m = in.nextInt();
		n = in.nextInt();
		
		int result;
		try {
			result = m / n;	
			System.out.println(result);
		} catch (ArithmeticException ae) {
			System.out.println("Divisor cannot use 0!!!");
		}
		
		in.close();
		
		System.out.println("Mark the next step of operation!");

The above is what I defined when I encountered a divide by zero error, using try catch method -- try {statements that may have exceptions;} catch (wrong class parameter) {statement executed when an exception is encountered}. The advantage of using this method is that you can continue to run the following statements after encountering and grabbing exceptions, rather than ending the operation directly! As follows:If you throw an exception with threw, you will end the operation directly!

The following three diagrams compare the program flow under different conditions:

Runtime and non runtime exceptions

Many exception classes have been defined inside Java

Abnormal operation time and non abnormal operation time can be divided into two categories; For non runtime exceptions, the Java compiler needs to program itself to handle exceptions, otherwise it cannot compile. For runtime exceptions, there is no need for the programmer to handle exceptions. When the program encounters exceptions, it will stop running immediately, and then hand it over to the JVM for processing!

Custom exception

When necessary, we can define our own Exception class. When we use Exception class as the base class, the Exception we define is "check type Exception", and the Exception derived from RuntimeException is "runtime Exception". It is suggested to define check type exceptions to facilitate programmers to grab and handle exceptions. How to define an Exception class is relatively simple. We can choose Exception as the base class to derive our own Exception class, as follows:

public class TestRun extends Exception {

	public TestRun() {
		// TODO Auto-generated constructor stub
	}

	public TestRun(String arg0) {
		super(arg0);
		// TODO Auto-generated constructor stub
	}

	public TestRun(Throwable arg0) {
		super(arg0);
		// TODO Auto-generated constructor stub
	}

	public TestRun(String arg0, Throwable arg1) {
		super(arg0, arg1);
		// TODO Auto-generated constructor stub
	}

	public TestRun(String arg0, Throwable arg1, boolean arg2, boolean arg3) {
		super(arg0, arg1, arg2, arg3);
		// TODO Auto-generated constructor stub
	}

The labeled TODO is our own exception handling. In the primary stage, we can delete it and choose to use the method of the prepared base class.

The reason why there is an exception here is that you need a serial number to ensure the serializability of the exception class!

After adding, you can complete a custom exception class. Let's test it:

public static void main(String[] args)  {
		System.out.println("Before the exception occurs !");
		
		Complex c1 = new Complex(1.3, 1.5);
		Complex c2 = new Complex(0.0, 0.0);
	try {
		c1.div(c2);
		System.out.println("The exception happened!");
	} catch(ComplexDividedByZeroException ce){
		System.out.println("Divide by zero!");
	} finally {
		System.out.println("The exception happened!");
	}
		System.out.println("After the exception occurs !");
	}

You can see the exception class defined by ourselves, and you can also complete exception handling.

Selection of exception handling

There are two options for exception handling: throw and grab. Generally speaking, if an exception is handled in this method, and the exception is no longer thrown to the upper method (the method calling this method), we choose to grab the exception. If this method does not handle its arrangement, it can be divided into two cases. One is that this exception will not affect the logic and execution of subsequent code, so it can be directly captured and nothing can be written in catch. The other is that it will have a great impact, so we need to throw exceptions and throw them level by level to terminate the program, so as not to affect the operation of the subsequent program.

There is also a simple processing method: if it can be processed, it will be processed, and if it cannot be processed, it will be thrown!

finally in exception

In our custom exception test, there is such a code:

try {
		c1.div(c2);
		System.out.println("Exception did not occur!");
	} catch(ComplexDividedByZeroException ce){
		System.out.println("A division by zero error has occurred!");
	} finally {
		System.out.println("The exception happened!");
	}

This is a structure to grab exceptions, but there is a special finally keyword. Its meaning is that the statements in finally will be executed no matter whether the exception occurs or not. We can put the statements that must be executed when the exception occurs in finally! Such as closing resources.

In the future, more and more programming, we will slowly realize the connotation of exception handling!

Topics: Java JavaSE