Java exception and error handling basics

  • 2020-04-01 02:27:23
  • OfStack

Exceptions and errors:
abnormal : in Java program error is mainly grammar and semantic errors, a program in compiling and running of the mistakes we unified call is unusual, it is the VM (virtual machine) notify you one way, in this way, the VM to let you know, you (developer) have made a mistake, now has a chance to modify it. Exception classes are used in Java to represent exceptions, and different exception classes represent different exceptions. But all exceptions in Java have a base class called Exception.
error : it refers to a serious problem that a reasonable application cannot intercept. Most of them are abnormal. An error is a failure of the VM (although it can be any system-level service). So, errors are hard to handle, and the average developer (not you, of course) can't handle them, such as memory leaks. As with exceptions, errors are represented in Java by error classes, with different error classes representing different errors. But all errors in Java have a base class called Error.
To sum up, we can know that the most essential difference between exceptions and errors is that exceptions can be handled by developers, while errors are built into the system, which generally cannot be handled and do not require us to handle them.
1. An exception is an event that occurs during the execution of a program and interrupts the operation of normal instructions
2. Error, an action or instance that deviates from acceptable code behavior
Structural classification of anomalies:
1. Runtime exception (not checked)
2. Compile-time exceptions (checked exceptions)
Running an exception is RuntimeException; The rest are compilation exceptions
Exception and Error have a common parent class Throwable in Java.
Error  The Exception
RuntimeException has several subclasses
1, Java. Lang. ArrayIndexOutOfBoundsException
Array index out of bounds exception. Thrown when the index value of an array is negative or greater than or equal to the array size.
2, Java. Lang. ArithmeticException
Arithmetic condition exception. An integer divided by zero, etc.
3, Java. Lang. NullPointerException
Null pointer exception. This exception is thrown when the application attempts to use null where the object is required. For example, calling instance methods of null objects and accessing null objects
Properties, calculating the length of a null object, throwing null using a throw statement, and so on
4, Java. Lang. ClassNotFoundException
The class exception could not be found. Throws when an application tries to construct a class by its class name as a string, and after traversing the CLASSPAH it cannot find a class file with the corresponding name
The exception.
Exception handling:
Catch the try {} {}
Try {}catch{}finally{} finally code blocks are executed with or without exceptions
Try {}finally{} can also be used in combination, but catch{}finally{} cannot
Note: in an inheritance relationship, a child class overrides a parent class's methods and cannot throw an exception more broadly than the parent class

Use of exceptions
In the use of exceptions in this part is mainly demo code, we are usually in the process of writing code will encounter (of course, only a small part), throw away!

Example 1. This example mainly compares two methods to demonstrate the execution flow of the code with the exception.


public static void testException1() {
int[] ints = new int[] { 1, 2, 3, 4 };
System.out.println(" Before the anomaly ");
try {
System.out.println(ints[4]);
System.out.println(" Am I still lucky enough to carry it out ");//After an exception occurs, the following code cannot be executed
} catch (IndexOutOfBoundsException e) {
System.out.println(" Array overbounds error ");
}
System.out.println(" After the anomaly ");
}

  The following code   Copy the code  
public static void testException2() {
int[] ints = new int[] { 1, 2, 3, 4 };
System.out.println(" Before the anomaly ");
System.out.println(ints[4]);
System.out.println(" Am I still lucky enough to carry it out ");//After an exception occurs, the code behind it cannot be executed
}


 
First pointed out the deficiency in example, IndexOutofBoundsException is a non tested is unusual, so don't try... The catch... Display capture, but my goal is to handle the same exception differently and see how it turns out. When an exception occurs, the first method just jumps out of the try block, but the code behind it executes just the same. But the second one is a little bit different and goes out of the way and is a little bit tougher. From the first method we can see that try... The catch... It is a "transactional" safeguard that is intended to ensure that the program will run out of exceptions, and it also tells the programmer details of what went wrong in the program (which sometimes depends on the programmer's design).
Example 2. Rethrow an exception

public class Rethrow {
public static void readFile(String file) throws FileNotFoundException {
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.err.println(" Not knowing how to handle the exception or not wanting to handle it at all, but not doing so is not appropriate Rethrow an exception To the next level ");
//Rethrow an exception
throw e;
}
}

public static void printFile(String file) {
try {
readFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
printFile("D:/file");
}
}
 

Exceptions are meant to be nice and let us try to fix the program, but in reality we have very little chance of fixing it, and we use them a lot to record things that go wrong. If you're tired of constantly handling exceptions, rethrowing them can be a great relief. Toss the exception intact to the next level, to the person calling the method, and let him do the thinking. In this way, Java exceptions (meaning checked exceptions, of course) are a lot of trouble, even though they are well-intentioned.

Example 3. Use of exception chain and exception loss


ExceptionA,ExceptionB,ExceptionC
public class ExceptionA extends Exception {
public ExceptionA(String str) {
super();
}
}

public class ExceptionB extends ExceptionA {

public ExceptionB(String str) {
super(str);
}
}

public class ExceptionC extends ExceptionA {
public ExceptionC(String str) {
super(str);
}
}


 
Abnormal loss:

public class NeverCaught {
static void f() throws ExceptionB{
throw new ExceptionB("exception b");
}

static void g() throws ExceptionC {
try {
f();
} catch (ExceptionB e) {
ExceptionC c = new ExceptionC("exception a");
throw c;
}
}

public static void main(String[] args) {
try {
g();
} catch (ExceptionC e) {
e.printStackTrace();
}
}

}

 

Why did it just print ExceptionC and not print ExceptionB? This or oneself analysis!
The above situation is equivalent to missing an exception, which is very unfavorable in our process of troubleshooting. So what should we do in the above situation? This is where the exception chain comes in: save the exception information and throw another exception without losing the original exception.


public class NeverCaught {
static void f() throws ExceptionB{
throw new ExceptionB("exception b");
}

static void g() throws ExceptionC {
try {
f();
} catch (ExceptionB e) {
ExceptionC c = new ExceptionC("exception a");
//Abnormal even
c.initCause(e);
throw c;
}
}

public static void main(String[] args) {
try {
g();
} catch (ExceptionC e) {
e.printStackTrace();
}
}

}

 

This exception chain is characteristic of all exceptions, because the initCause() method is inherited from Throwable.
Example 4. Cleaning up
Cleaning up is essential for us, because if there are some resource-consuming operations, such as IO,JDBC, etc. If we don't close it properly when we're done with it, the consequences can be severe, which means memory leaks. The occurrence of exceptions requires us to design a mechanism for resources to be cleaned up in a timely and correct manner in all cases. This is finally.


public void readFile(String file) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
// do some other work
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


 
The example is very simple and is an example of reading a file. Such examples are also common in JDBC operations. Therefore, I think the timely and correct cleaning of resources is one of the basic qualities of a programmer.
The Try... Finally structures are also a means of ensuring that resources are shut down correctly. If you don't know what will happen during code execution that will prevent the resource from being cleaned up, wrap the "suspicious" code with a try and clean up the resource in finally. Here's an example:

public void readFile() {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream("file")));
// do some other work

//close reader
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} 
}
 

Let's note the difference between this method and the previous one. The next person may be better at shutting down reader early. This often backfires because exceptions can occur at any time before reader.close(), and this code structure does not prevent any exceptions. Because the program will pop up where the exception occurs, the subsequent code cannot execute (this has been demonstrated above). We can use try... Finally to transform:


public void readFile() {
BufferedReader reader = null;
try {
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream("file")));
// do some other work

// close reader
} finally {
reader.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

It's a good idea to turn off resources early, because the longer you wait, the more likely you are to forget to turn them off. So try... Finally is guaranteed to be foolproof (and don't bother, that's how Java works).
On the other hand, if I want to open a file or create a JDBC connection in the constructor, we cannot close the resource early in the constructor because we are using the resource in other methods. Are we at the end of our tether? The answer is no. Take a look at the following example:

public class ResourceInConstructor {
BufferedReader reader = null;
public ResourceInConstructor() {
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream("")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

public void readFile() {
try {
while(reader.readLine()!=null) {
//do some work
}
} catch (IOException e) {
e.printStackTrace();
}
}

public void dispose() {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


 
There's a little more to this section, but exceptions are things that seem easy to use, and there's a lot more to dig into in Java


Related articles: