Let’s look at a simple example program to see what exception handling in Java is

Use the try and catch

Take a look at this program:

package ExceptionNote;

import java.util.Scanner;

public class Average {

	public static void main(String[] args) {
		
		Scanner console = new Scanner(System.in);
		double sum = 0;
		int count = 0;
		while(true) {
			int number = console.nextInt();
			if(number == 0)
				break;
			sum += number;
			count++;
		}
		System.out.printf("Average %.2f%n",sum/count); }}Copy the code

This program lets the user enter any integer, ending with 0, and displaying the average value of the input integer. Let’s do a simple test

  • If the user enters each integer correctly, naturally, the program displays the results smoothly

  • If the user makes a mistake, the following error message appears

InputMismatchException means that the input doesn’t meet the requirements, because the program says int, we said aaa,String, So an InputMismatchexception is raised

All of the exception error messages in Java are packaged into objects, where try catches come in handy.

package ExceptionNote;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Average2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			Scanner console = new Scanner(System.in);
			double sum = 0;
			int count = 0;
			while(true) {
				int number = console.nextInt();
				if(number == 0)
					break;
				sum += number;
				count++;
			}
			System.out.printf("Average %.2f%n",sum/count);
			
		} catch(InputMismatchException ex) {
			System.out.println("please input the integer"); }}}Copy the code

After the trycatch statement is added, when we encounter incorrect input, we will see something like this

The JVM tries to execute the code in a try. If an error occurs, the execution process jumps away from the point at which the error occurred, and then compares the type of error declared in the catch to the type of the object that was thrown. If so, the program code executes the catch block.

Exception inheritance architecture

Many people don’t understand when this code prompts an error

This is because the compiler considers calling this method to be error-prone and requires you to make sure you catch errors in your program. There are two ways to handle this error. The first is to catch the error using the previous trycatch statement, and the second is to throw the error directly after the function.

But at the same time, the question arises. Why didn’t the previous Average program force us to deal with errors?

To solve this problem, you must first understand the inheritance architecture of the faulty objects.

  • The Throwable class defines methods to get error messages, stack traces, and so on. It has two subclasses. Java. Lang. Error and Java. Lang. Exception.

Error and its subclass instances typically represent serious system errors, such as hardware level errors, JVM errors, or memory errors. Trycatch can of course be used to handle this, but it is not recommended because the program itself is helpless when a serious system error occurs.

** If a Throwable object is thrown, and no catch is found in the program, and the JVM eventually catches the throwable object, the JVM basically displays the packing information for the throwable object and interrupts the program. **

Subject (Checked Exception)

Exception or its children that are not part of RunTimeException or its children are examined. Object that is checked by the compiler. The purpose of this is that when the API designer requires that a method be implemented and certain conditions are true, an error is raised, and the client calling the method is thought to be capable of handling the error, requiring the compiler to tell the client that it must explicitly handle the error, or it cannot compile.

A derived class instance of a RuntimeException that represents a condition that raises an error and needs to be carefully checked when the API designer implements a method. Also called an unchecked exception.

Also pay attention to the order in which exception objects are caught. If the superclass exception comes before the subclass exception, then obviously the subclass exception will never be caught.

To catch or to throw

Here is an example of reading a plain text document

package ExceptionNote;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileUtil {
	public static String readFile(String name)  {
		StringBuilder text = new StringBuilder();
		try {
			Scanner console = new Scanner(new FileInputStream(name));
			while(console.hasNext()) {
				text.append(console.nextLine()).append('\n');
			}
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		}
		returntext.toString(); }}Copy the code

The problem is, if this function is used on a Web site, the error will be displayed on the console. How will the Web user see it? Therefore, it is not necessary to write exceptions or output error messages directly on catch.

This is a good time to consider throwing an exception. If an exception occurs during the method design process and you don’t have enough information at design time to know how to handle it, you can throw an exception and let the calling client handle it.

You can actually use a try catch for some of the exception handling at the same time, and throw the rest that can’t be handled

package ExceptionNote;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileUtil {
	public static String readFile(String name) throws FileNotFoundException {
		StringBuilder text = new StringBuilder();
		try {
			Scanner console = new Scanner(new FileInputStream(name));
			while(console.hasNext()) {
				text.append(console.nextLine()).append('\n');
			}
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
			throw ex;
		}
		returntext.toString(); }}Copy the code

Keep in mind that if a checked exception is thrown, you must use the throws declaration on the method, but not if it is a non-checked exception.