Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of exception capture and handling in java

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article shares with you the content of sample analysis of exception capture and handling in java. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

I. brief introduction of Java exception

What is an anomaly?

The unexpected event that occurs when the program is running, which prevents the program from executing as expected by the programmer, is an exception. When an exception occurs, the program is left to fend for itself and immediately exits and terminates. In Java, an error that occurs when Java is compiled or run or run.

Java provides an even better solution: exception handling.

The exception handling mechanism enables the program to deal with the exception pertinently according to the pre-set exception handling logic of the code when the exception occurs, so that the program can return to normal and continue to execute as much as possible, and keep the code clear.

The exception in Java can be thrown when the statement in the function is executed, or it can be thrown manually by the programmer through the throw statement. Whenever an exception is generated in the Java program, an exception object of the corresponding type will be used to encapsulate the exception, and JRE will try to find an exception handler to handle the exception.

Several keywords used in the Java exception mechanism: try, catch, finally, throw, throws.

Try-used to monitor. The code to be listened for (the code that may throw an exception) is placed within the try statement block, and when an exception occurs within the try statement block, the exception is thrown.

Catch-used to catch exceptions. Catch is used to catch exceptions that occur in try statement blocks.

Finally-- finally statement blocks are always executed. It is mainly used to recover material resources (such as database connections, network connections and disk files) opened in try blocks. Only after the execution of the finally block, will you come back to execute the return or throw statements in the try or catch blocks. If the statements with termination methods such as return or throw are used in the finally, the execution will not be skipped back and will be stopped directly.

Throw-used to throw an exception.

Throws-used in method signatures to declare exceptions that may be thrown by the method. You can also use throws to throw on the main method. If throws throw is used on the main method, it means that there is no mandatory exception handling in the main method, and if an exception occurs, it will be handed over to JVM for default handling, which will cause the program to interrupt execution.

The cause of the exception:

The user entered illegal data.

The file to be opened does not exist.

The connection is interrupted during network communication, or the JVM memory overflows.

Some of these exceptions are caused by user errors, some are caused by program errors, and others are caused by physical errors.

Three types of exceptions:

Checking exceptions: the most representative checking exceptions are those caused by user errors or problems, which programmers cannot foresee. For example, when you want to open a nonexistent file, an exception occurs, and these exceptions cannot be simply ignored at compile time.

Runtime exceptions: run-time exceptions are exceptions that may be avoided by programmers. In contrast to checked exceptions, run-time exceptions can be ignored at compile time.

Error: an error is not an exception, but a problem that is out of the programmer's control. Errors are usually ignored in the code. For example, when the stack overflows, an error occurs that cannot be checked in the compilation.

II. Classification of Java anomalies

The abnormal root interface Throwable, under which there are two subinterfaces, Error and Exception.

Error: refers to a JVM error. The program is not executed and cannot be handled.

Exception: refers to the exception generated during the running of the program, which can be handled by the user in a processing format.

Java built-in exception class

The Java language defines some exception classes in the java.lang standard package.

Subclasses of standard runtime exception classes are the most common exception classes. Because the java.lang package is loaded into all Java programs by default, most of the exceptions inherited from the runtime exception class can be used directly.

Java also defines some other exceptions based on each class library, and the non-checking exceptions for Java are listed in the table below.

Exception description ArithmeticException throws an exception when the operation condition of the exception occurs. For example, when an integer is divided by zero, an instance of this class is thrown. The exception that ArrayIndexOutOfBoundsException throws when accessing an array with an illegal index. If the index is negative or greater than or equal to the array size, the index is illegal. The exception that ArrayStoreException throws when it attempts to store an object of the wrong type in an array of objects. ClassCastException throws this exception when it attempts to cast an object into a subclass that is not an instance. The exception thrown by IllegalArgumentException indicates that an illegal or incorrect parameter was passed to the method. The exception thrown by IllegalMonitorStateException indicates that a thread has tried to wait for the monitor of the object, or to notify other threads that are waiting for the object without specifying the monitor itself. A signal generated by IllegalStateException when a method is called at an illegal or inappropriate time. In other words, the Java environment or Java application is not in the appropriate state required by the request operation. The exception that is thrown when the IllegalThreadStateException thread is not in the appropriate state required by the requested operation. IndexOutOfBoundsException indicates that a sort index, such as sorting an array, string, or vector, is thrown when it is out of range. NegativeArraySizeException throws this exception if the application attempts to create an array of negative size. NullPointerException throws the exception NumberFormatException when the application attempts to use null where the object is needed. The exception is thrown when the application attempts to convert a string to a numeric type, but the string cannot be converted to the appropriate format. SecurityException an exception thrown by the security manager that indicates a security violation. StringIndexOutOfBoundsException this exception is thrown by the String method, indicating that the index is either negative or exceeds the size of the string. UnsupportedOperationException throws this exception when the requested operation is not supported.

The following table lists the checked exception classes that Java defines in the java.lang package.

Exception description when a ClassNotFoundException application tries to load a class, the corresponding class is not found and the exception is thrown. CloneNotSupportedException throws this exception when the object is cloned by calling the clone method in the Object class, but the object's class cannot implement the Cloneable interface. This exception is thrown when IllegalAccessException refuses to access a class. InstantiationException throws this exception when it attempts to create an instance of a class using the newInstance method in the Class class, and the specified class object cannot be instantiated because it is an interface or an abstract class. InterruptedException this exception is thrown when one thread is interrupted by another thread. The NoSuchFieldException request variable does not exist. The NoSuchMethodException request method does not exist.

Abnormal method

The following list is the main method of the Throwable class:

Serial number method and description 1public String getMessage ()

Returns details about the exception that occurred. This message is initialized in the constructor of the Throwable class. 2public Throwable getCause ()

Returns a Throwable object that represents the cause of the exception. 3public String toString ()

Use the result of getMessage () to return the cascade name of the class. 4public void printStackTrace ()

Print the toString () result and stack hierarchy to System.err, the error output stream. 5public StackTraceElement [] getStackTrace ()

Returns an array containing the stack hierarchy. The element with the subscript 0 represents the top of the stack, and the last element represents the bottom of the method call stack. 6public Throwable fillInStackTrace ()

Populate the Throwable object stack hierarchy with the current call stack hierarchy and add it to any previous information in the stack hierarchy. Third, the use and execution process of exceptions

1. Exception handling scheme

Try...catch 、 try...catch...finally 、 try...finally

Try {

Exceptions that may occur

} catch (exception type exception name (variable)) {

Code that handles exceptions

} catch (exception type exception name (variable)) {

Code that handles exceptions

}...

[finally {

Release resource code

}]

Note:

Catch cannot exist independently of try.

Catch cannot be without content.

Adding a finally block after try/catch is not mandatory.

Try code cannot be followed by neither catch nor finally blocks.

The less in try, the better.

No code can be added between try, catch, and finally blocks.

The code in finally must be executed eventually (except for JVM exit)

If the program may have more than one exception, multiple catch are needed to catch it.

If the exception is a sibling relationship, it doesn't matter who comes before or after catch.

If there is a superior-subordinate relationship between exceptions, the superior needs to put it behind.

2. Exception execution process

The difference between Error and Exception:

Error (error) is an error in the system, which the programmer cannot change and deal with. It is an error that occurs when the program is compiled and can only be corrected by modifying the program. It generally refers to the problems related to the virtual machine, such as system crash, virtual machine error, insufficient memory space, method call stack overflow and so on. For the interruption of the application caused by this kind of error, the program itself cannot recover and prevent. If you encounter such an error, it is recommended that the program be terminated.

Exception (exception) represents an exception that the program can handle, can be caught and may be recovered. If you encounter such an exception, you should handle the exception as much as possible to make the program run again, instead of terminating the exception at will.

When catch catches an exception, why not consider using the Throwable type and just use Exception for receiving?

Throwable represents a larger range than Exception. In fact, the program uses Throwable for processing, there are no syntax problems, but there will be logic problems. Because what appears at this time (or the user can handle) is only the Exception type, and if you use Throwable to receive, it will also mean that you can handle Error errors, while users cannot handle Error errors, so the exceptions that users can handle in development are required to be dominated by exception classes.

Should exceptions be handled together or separately?

According to whether the actual development requirements are strict or not. In the actual project development project work, whether all exceptions are handled using Exception or separately, it is completely decided according to the developer's project development standards. If the project development environment is rigorous, it is basically required to handle each exception separately, and record the time and location of the exception in detail, which can facilitate program maintenance personnel to maintain the code. Note again: when dealing with multiple exceptions, small exceptions should be handled before large exceptions are caught.

The difference between throw and throws?

Throw and throws are both keywords used in exception handling. The differences are as follows:

Throw: refers to the artificial throwing of an exception object in a method (this exception object may be instantiated by itself or throw an existing one)

Throws: used on the declaration of a method, indicating that the method must handle an exception when called.

The difference between checked exception (Checked Exception) and non-checked exception (Unchecked Exception)?

All checked exceptions inherit from java.lang.Exception; all non-checked exceptions inherit from java.lang.RuntimeEx ception.

The main difference between checking exception and non-checking exception lies in the way it handles the exception: checking exception must be handled with keywords such as try catch or throws, otherwise the compiler will report an error; non-checking exception is generally a problem caused by the lack of rigorous writing of program code, which can be avoided by modifying the code.

Common runtime exceptions: null pointer exception (NullPointerException), divide by zero exception (ArithmeticException), array out of bounds exception (ArrayIndexOutOfBoundsException), etc.

Common inspection exceptions: input and output exception (IOException), file non-exception (FileNotFoundException), SQL statement exception (SQLException) and so on.

Assert keyword (understand)

In Java, the assert keyword was introduced from JAVA SE 1.4. to avoid errors caused by the use of the assert keyword in older versions of Java code, Java defaults to not starting assertion checking when executing. (at this point, all assertion statements are ignored! If you want to turn on assertion checking, you need to turn it on with the switch-enableassertions or-ea.

The assert keyword syntax is simple and can be used in two ways:

Assert

If true, the program continues execution.

If false, the program throws an AssertionError and terminates execution.

Assert:

If true, the program continues execution.

If false, the program throws java.lang.AssertionError and enters it.

For example:

Public class Test {public static void main (String [] args) {int a = 10; int b = 2; assert a = 10: "an is not equal to 10"; System.out.println ("a =" + a);}}

The execution result is:

Public class Test {public static void main (String [] args) {int a = 10; int b = 2; assert a = 20: "an is not equal to 20"; System.out.println ("a =" + a);}}

The execution result is:

IV. Custom exception

You can customize exceptions in Java. If you want to customize the exception class, you can extend the Exception class, so such custom exceptions belong to the check exception (checked exception). If you want to customize unchecked exceptions, extend from RuntimeException.

According to international practice, a custom exception should always contain the following constructor:

A no-parameter constructor

A constructor with a String argument and passed to the constructor of the parent class.

One takes a String parameter and a Throwable parameter and is passed to the parent class constructor

A constructor with a Throwable argument and passed to the constructor of the parent class.

The following is the complete source code of the IOException class, which you can learn from.

Package java.io; public class IOException extends Exception {static final long serialVersionUID = 7818375828146090155L; public IOException () {super ();} public IOException (String message) {super (message);} public IOException (String message, Throwable cause) {super (message, cause);} public IOException (Throwable cause) {super (cause);}}

Finally blocks and return

First of all, a fact that is not easy to understand: even if there are statements such as return,break,continue in the try block that change the execution flow, finally will execute.

The return in finally overrides the return value in try or catch.

The return or exception in finally suppresses (eliminates) the exception in the previous try or catch block.

Thank you for reading! This is the end of this article on "sample analysis of exception capture and handling in java". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report