Common exception types and causes

This is the 9th day of my participation in the November Gwen Challenge. See details: The Last Gwen Challenge 2021.

About the author

  • The authors introduce

🍓 Blog home page: author’s home page 🍓 Introduction: 🥇, a high quality creator in JAVA field, 🎓, a junior in college, participated in various provincial and national competitions and won a series of honors. 🍓 pay attention to me: pay attention to my learning materials, document download all have, regularly update the article every day, inspirational to do a JAVA senior program ape 👨💻.


SQLException: Operates the database exception class.

Most Java applications today rely on databases to run. This class is triggered when an error occurs when a Java application communicates with the database. It also displays database error messages to the user. In other words, the operational database exception class acts as a bridge between the database and the user for passing exception information. For example, when a user inserts data into the system, a field in the database must be unique. When the user inserts data, if the value of the field is the same as the value of the existing record, violating the database’s uniqueness constraint, the database will run an exception message. This information may not be visible to the average user because it happens at the database level. At this point, the operation database exception class will catch the exception information of the database and pass the exception information to the foreground. In this way, the foreground user can analyze the cause of the error based on the exception information. This is the primary purpose of this action database exception class. In Java applications, this class is triggered when all database operations fail. All of the Java application’s own prompts at this point tend to be too general, saying that there was an error interacting with the database, without much reference. Instead, the prompt information of the database is more valuable.

ClassCastException: Data type conversion exception.

In Java applications, sometimes you need to convert data types. This transformation includes both explicit and implicit transformations. However, no matter how to convert, it must meet a prerequisite condition, that is, data type compatibility. If this principle is violated during a data conversion, a data type conversion exception is raised. For example, in the current application, the developer needs to convert a character date data to the date data that the database can accept, this time only need to control in the foreground application, generally no problem. However, if the foreground application lacks relevant controls, for example, the user enters only the month and day information, not the year information, when entering the date. An exception will occur when the application performs a data type conversion. According to the author’s experience, the data type conversion exception is a relatively low-level exception that occurs more frequently in application development. For the most part, you can impose some control over data types in the application window. That is, data type compatibility is guaranteed before the data type is converted. In this way, it is less likely to cause data type conversion exceptions. For example, in fields that only allow numeric types, you can set the user to not be allowed to enter characters other than numeric values. The exception handling mechanism ensures that the application will not be run incorrectly. However, in actual development, it is necessary to anticipate the causes of errors as much as possible and avoid exceptions as much as possible.

NumberFormatException: An exception thrown when a string is converted to a number type.

If a problem occurs during a conversion from a character to a number, a separate exception, NumberFormatException, is used in the Java program for this exception. For example, it is allowed to convert character data “123456” into numeric data. However, if the character data contains non-numeric characters, such as 12#456, the conversion to numeric will be an exception. The system catches the exception and handles it.

There are many more common exception classes in Java applications. For example, the corresponding class exception was not found, some class exceptions were not allowed to be accessed, the file was ended, the file was not found, the field was not found, and so on. A typical system developer can use this exception name to determine the type of exception currently in use. Not bad, but a good memory is worse than a bad pen. At the end of the day, the application developer has a list of exceptions at hand when necessary (especially if there are custom exceptions). In this way, the application can find the cause of an exception in a timely manner based on the name of the exception, whether the application finds a problem during debugging or receives a complaint from a user. In this way, exceptions can be resolved in the shortest time and normal operation of applications can be restored. This measure has been used by the author for many years and is very effective.

Catch exceptions and handle them

An instruction flow that causes a program to interrupt execution when an exception occurs. If the program is abnormal and not properly handled, the program will terminate.

Observe programs that do not generate exceptions

public class TestDemo1{
	public static void main(String args[]){
		System.out.println("1. Division program begins");
		int result =10/2;
		System.out.println(2. Result of division program:+result);
		System.out.println("3. End of division procedure"); }}/* 1, division program start 2, division program result: 5, division program end */
Copy the code

The program that generates the exception

public class YiChang{
	public static void main(String args[]){
		System.out.println("1, division begins.");
		int result =10/0;// An error occurs
		System.out.println(2. Result of division program:+result);
		System.out.println("3. End of division."); }}/* Exception in thread "main" java.lang.ArithmeticException: / by zero at YiChang.main(YiChang.java:5) */
Copy the code

This time there was an error in the program, so the program is not executed after the error, but directly carried out the output of the error message, and directly ended the program, but there is an error, should go to deal with it, but now there is no processing.

Handle exceptions

Now, if you want the program to complete normally after an exception occurs, you can use the following format for exception handling;

		try{possible exception statements}[catch(Exception type Exception object){Handle exceptions; }catch(Exception type Exception object){Handle exceptions; }... ] [finally{exception unified exit executes this code regardless of whether an exception occurs; }]Copy the code

Use this operation to handle exceptions

What finally does: For languages that do not have garbage collection and automatic calls to structural functions (destructors: functions that are called when objects are no longer in use), finally statements are important because they allow programmers to ensure that no matter what happens in the try block, memory is always freed. But Java has garbage collection, so memory release is no longer an issue, and Java has no destructors to call.

When can you finally be used? Of course, if you want to restore resources other than memory to the accident state. Resources that need to be cleaned up include: open files or network connections, graphics drawn on the screen, or even an external switch.

public class TestDemo1{
	public static void main(String args[]){
		System.out.println("1. Division program begins");
		try{
			int result =10/0;
			System.out.println(2. Result of division program:+result);
		}catch(ArithmeticException e){
		System.out.println("Exception handled correctly.");
		}
		System.out.println("3. End of division procedure"); }}/* the exception is handled correctly when the division program starts
Copy the code

It can be found that after exception processing is added, even if there is an exception in the program, the program can be normally executed. However, it is found that the error information output during exception processing is not clear compared with before. Therefore, in order to make the error information more complete, generally speaking, The printStackTrace() method is called to print the exception information

This method (printStackTrace) prints the most complete exception:

try{
	int x = 10/0;     / / exception
	System.out.println(2. Result of division program:+x);
}catch(ArithmeticException e){
	e.printStackTrace();
}

Copy the code

Try catch finallly operation

public class TestDemo1{
	public static void main(String args[]){
		System.out.println("1, division begins.");
		try{
			int x = 10/0;     / / exception
			System.out.println(2. Result of division program:+x);
		}catch(ArithmeticException e){
			e.printStackTrace();
		}finally{
			System.out.println("Execute regardless of exception.");
		}
		System.out.println("3. End of division."); }}Copy the code

However, there is a problem with the previous program: now the two parameters to perform the math calculation are provided by the program by default, so what if the two parameters to perform the math calculation are passed through the initialization parameters?

public class TestDemo2{
	public static void main(String args[]){
		System.out.println("1, division begins.");
		try{
			int x = Integer.parseInt(args[0]);	// Receive parameters
			int y = Integer.parseInt(args[1]);    // Receive parameters
			int result = x/y;   
			System.out.println(2. Result of division program:+result);
		}catch(ArithmeticException e){
			e.printStackTrace();
		}finally{
			System.out.println("Execute regardless of exception.");
		}
		System.out.println("3. End of division."); }}Copy the code

When it is found that the data is transmitted externally, then in this case, there may be several kinds of problems:

  • Perform without input parameters and ArrayIndexOutOfBoundsException, untreated.

  • The input argument is not a number, NumberFormatException, not processed.

  • The dividend is 0 ArithmeticException, processed.

It can be found that the above program actually has three kinds of exceptions, and the program can only handle one of them, and for the exception that cannot be handled, the discovery program will still directly interrupt the execution.

public class TestDemo2{
	public static void main(String args[]){
		System.out.println("1, division begins.");
		try{
			int x = Integer.parseInt(args[0]);	// Receive parameters
			int y = Integer.parseInt(args[1]);    // Receive parameters
			int result = x/y;   
			System.out.println(2. Result of division program:+result);
		}catch(ArithmeticException e){
			e.printStackTrace();
		}catch(ArrayIndexOutOfBoundsException e){
			e.printStackTrace();
		}catch(NumberFormatException e){
			e.printStackTrace();
		}finally{
			System.out.println("Execute regardless of exception.");
		}
		System.out.println("3. End of division."); }}Copy the code

At this point, the problem is that if you do the same thing over and over again, you might as well write if.. The else.

Process for handling exceptions

The basic processing process of exceptions has been completed above, but problems can also be found. It seems to be an impossible task to judge all the exceptions as before, because I will surely come into contact with some uncommon exception information in the future. Therefore, we must first study the process and structure of exceptions.

Start by looking at the inheritance structure of the two exceptions

ArithmeticException
java.lang.Object
java.lang.Throwable
java.lang.Exception java.lang.RuntimeException
java.lang.ArithmeticException
    

ArrayIndexOutOfBoundsException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.IndexOutOfBoundsException
java.lang.ArrayIndexOutOfBoundsException

Copy the code

The highest inherited class in which all exception types can be found is Throwable. The doc documentation shows that there are two subclasses of Throwable:

Error: a JVM Error in which the program is not executed and cannot be handled.

Exception: Refers to the error message in the program, can be handled Exception, mainly concerned with Exception.

Therefore, it can be found through the inheritance relationship that exceptions must be the main Exception in daily processing, and the following Exception processing process can be formed at this time.

Throw a keyword

Throws keyword is mainly used in method definition, indicating that exception handling is not performed in this method and is handed over to the called.

class MyMath{
    The div() method now throws an exception, indicating that all exceptions are handled by the caller.
	public int div(int x,int y) throws Exception{
			returnx/y; }}public class TestDemo3{
	public static void main(String args[]){
		try{
			System.out.println(new MyMath().div(10.0));
		}catch(Exception e){ e.printStackTrace(); }}}Copy the code

When calling throws declaration method, exception handling operation must be used for exception processing, which is mandatory processing. Now the main method itself is also a method, so in fact, the main method can also continue to use throws exception.

class MyMath{
    The div() method now throws an exception, indicating that all exceptions are handled by the caller.
	public int div(int x,int y) throws Exception{
			returnx/y; }}public class TestDemo3{
	public static void main(String args[]) throws Exception{
		try{
			System.out.println(new MyMath().div(10.0));
		}catch(Exception e){ e.printStackTrace(); }}}Copy the code

This means that the exception is still being thrown up to the JVM for exception handling.

Please explain the difference between throw and throws.

  • A throw is used to manually throw an instantiation object of an exception class inside a method (this object can be custom or already exist).
  • Throws is mainly used on method declaration to explicitly tell the method of exceptions that may be generated, and the method may not handle exceptions. In other words, the method is used on method declaration, indicating that exception handling must be performed when the method is called.

Exception handling model

Now I think there are two things that are really useless. Finally, throw.

Now we need to define a div() method that has the following requirements:

Output a prompt message before performing the division operation.

After the division operation is complete, a message is displayed.

If an exception is generated in the middle, it should be handed over to the called for processing.

class MyMath{
	public static int div(int x, int y) throws Exception{
		int result = 0;
		// Do not write a catch statement
		// Execute first after the try block is executed finally after the block is executed
		Throws exception catch, and then executes in the catch statement of the main method
		try{
			System.out.println("Before do the division calculation");
			result = x / y;
		}finally{
			System.out.println("After performing the division calculation");
		}		
		returnresult; }}public class TestDemo4{
	public static void main(String args[]){
		try{
			System.out.println(MyMath.div(10.0));
		}catch(Exception e){ e.printStackTrace(); }}}Copy the code

RuntimeException

public class TestDemo4{
	public static void main(String args[]){
		String str = "123";
		intnum = Integer.parseInt(str); System.out.println(num*num); }}Copy the code

This method converts a string to a primitive data type and multiplies it, but let’s look at the definition of the parseInt() method:

Public static int parseInt(String s) throws NumberFomatException
Copy the code

A NumberFomatException is thrown on this method. If a throw is present, you must use a try… To see the inheritance structure of NumberFomatException, there is no mandatory processing.

java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.IllegalArgumentException
java.lang.NumberFormatException

Copy the code

NumberFormatException is a subclass of RuntimeException, and Java specifies that the exception type of RuntimeException can be handled selectively. In development, if no exception is handled, An exception is handed over to the JVM for default handling.

The difference between Exception and RuntimeException? What are the common runtimeExceptions?

  • Exception is a parent of RuntimeException, and exceptions defined using Exception must use Exception handling

  • RuntimeException can be handled selectively by the user

  • Common exceptions: A NumberFormatException, ClassCastException NullPointException ArithmeticException, ArrayIndexOutBoundException.

Assertion: assert

Assertions mean that after a program executes to a line, the result must be the expected result, and an assert keyword was added after JDK1.4.

public class DuanYan{	public static void main(String args[]){		int x = 10;		Assert x == 30:" X is not thirty "; System.out.println(x); }}
Copy the code

By default, assertions in Java do not appear in normally executing code, and if you want to enable assertions, you should have some options earlier.

Custom exception

In Java province has provided a lot of exception types, but in development, these are the exception type will not be able to meet the needs of development, so in some of the system architecture tends to provide some new exception types, to show some special error, and this kind of operation is called a custom exception class, and to realize the custom exception class, Then you can have a class that inherits Exception or RuntimeException.

class MyException extends Exception{	public MyException(String str){		super(str);	}}public class TestDemo5{	public static void main(String args[]) throws Exception{		throw new MyException("Own exception class");	}}
Copy the code

If you see an exception type you haven’t seen before, it’s basically a custom exception class.