Home  >  Article  >  Java  >  How to use Java exceptions and assertions

How to use Java exceptions and assertions

WBOY
WBOYforward
2023-04-20 08:31:061677browse

Java Exceptions

In Java, an exception object is always an instance of a Throwable subclass.

The Error class system describes internal errors and resource exhaustion situations in the Java operating system.

Errors caused by programming will lead to RuntimeException. Exceptions caused by other error reasons - for example, errors in a program that once ran correctly due to I/O errors will not cause RuntimeException exceptions.

Exceptions derived from RuntimeException include the following problems: 1> Wrong type conversion; 2> Array out-of-bounds access; 3> Trying to access a null pointer.

Exceptions that are not derived from RuntimeException include:

1〉An attempt to read data from behind the end of the file;

2〉An attempt to open an incorrectly formatted URL;

3〉Trying to use a string to construct a Class object, but when the class corresponding to the string does not exist;

The principle of handling RuntimeException is: if a RuntimeException occurs, it must be yours Error;

Different browsers can handle different types of URLs, so whether the URL format is incorrect depends on the specific environment, not just the program code;

The Java language specification lists any Subclasses of Error and subclasses of RuntimeException are called unchecked exceptions, while other exceptions are called checked exceptions;

Exceptions will only be thrown in the following 4 situations:

1〉Call a method that throws a "checked exception", such as the readLine method of the BufferReader class;

2〉An error occurred during the running of the program, and a " Checked exception";

3〉Program error, for example, a[-1]=0 will throw an "unchecked exception" such as array index out of bounds (ArrayIndex--OutOfBoundsException);

4〉An internal error occurred in the Java virtual machine or runtime library;

There is no need to declare an internal error in Java. A method must declare all "checked exceptions" it may throw. If you override a method from the parent class in your own subclass. What needs special attention is that if the parent class method does not throw any "checked exception" at all, the subclass can only do the same;

In Java, a method without the throws indicator cannot throw any Java exceptions have been checked;

For try/catch code blocks, if any code within the method throws an exception and its type is not specified in catch, the method will exit immediately;

Should catch and handle exceptions that are known how to handle (use catch), and pass exceptions that do not know how to handle (use throws);

For try/catch/finally code blocks, regardless of whether they are caught or not Exception, the code in the finally clause will be executed;

Although Java programmers must manually set the code in the finally clause to recycle resources, due to Java's built-in "garbage collection" mechanism, there are only a very small number of resources Only manual recycling is required;

The actionPerformed method cannot throw any checked exceptions;

Some tips for using the Java exception mechanism:

1〉Exception control cannot replace simple Testing, compared with executing simple tests, the time required to catch exceptions is much longer than the former, so exceptions should only be used under abnormal circumstances;

2〉Do not overly refine exceptions;

3〉Don’t suppress exceptions: You can use the following format: try { //code} catch (Exception e) { //empty}

4〉Don’t be shy about passing exceptions: for certain exceptions (such as calling FileInputStream constructor or readLine method), it is better to pass it than catch it. It is more appropriate to have a high-level method notify the user of an error or to abort an unsuccessful command.

Java Assertions

By default, Java assertions are turned off. It can be opened with -ea and closed with -da. The option -ea:... will turn on the assertion function of all classes in the default package. Turning on or off assertion is a function of the class loader;

-da and -ea options are suitable for those "systems without class loaders" class" has no effect. For these system classes, use the -enablesystemassertions/-esa option to turn on the assertion function;

Java assertion usage tips:

1>Assertion failure is a fatal, unrecoverable error;

2>Assertion checking is only used during program development and testing;

Therefore, assertions should not be used as signals to notify other parts of the program that recoverable errors have occurred, or assertions should be used as notifiers way. Java assertions should only be used to locate internal errors in the program during the testing phase;

Java assertions are a tool used during the testing and debugging phases, while logging is a strategic tool used throughout the entire life cycle of the program.

The following is a section from think in java

Violation guidelines

Use violations to do the following things:

(1) Fix the problem and call the method that caused the violation again.

(2) Calm down the situation and continue without retrying the method.

(3) Calculate some other result than the result you want the method to produce.

(4) Solve the problem as much as possible in the current environment, and re-throw the same violation into a more advanced environment.

(5) Solve problems as much as possible in the current environment, and re-throw different violations into a more advanced environment.

(6) Abort program execution.

(7) Simplify coding. If the violation scheme makes things more complicated, it will be very annoying, and it is better not to use it.

(8) Make your own libraries and programs more secure. This is both a "short-term investment" (to facilitate debugging) and a "long-term investment" (to improve the robustness of the application)

The above is the detailed content of How to use Java exceptions and assertions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete