Java Insights--Custom exceptions, assertions __java

Source: Internet
Author: User
Tags assert exception handling terminates throw exception throwable

1. Throw an exception

exceptions thrown by the Java run-time system

manually created and thrown as needed

artificially throwing an exception (must be thrown as an object of Throwable or its subclasses)

syntax Format: Throw exception class object;

For example: IOException e = new IOException ();

throw E; ( The program terminates immediately after executing the throw statement, and then looks for a catch clause in all the try blocks containing it to match its type. )

2. Declaration Discard Exception

Μ If the code in a method might generate an exception at run time, but it is not necessary in this method, or you cannot determine how to handle such an exception, you can discard the exception using the throws declaration;

Μ indicates that the method will not handle such an exception, which is handled by the caller of the method;

Μ means that the system will look for the appropriate exception handling code in the upper-method body that calls the method, and no longer proceed with the normal process of the method.

Μ declares the format of discarding exceptions
Type method name ([parameter table]) throws exception type, ... {
Method body;
}

3. Although Java's built-in exception handling can handle most common errors, users still need to establish their own exception types to handle special situations. You can then define your own exception classes by creating exception subclasses.

format: class name extendsexception{

...}

Analysis: Exception classes do not define any methods themselves. But it inherits some of the methods provided by Throwable. For example,

Public stringgetmessage (); public Voidprintstacktrace ();

4. In Java, the following factors need to be considered for handling exceptions:

Μ If an exception event is generated at run time and there is no exception object corresponding to the exception event in the JDK API, you should create an exception object for the user-defined type.

Μ If you can predict the type of an exception object and the exception occurs when the program is running, it is recommended that the system exception type defined in JDKAPI be applied and that the exception object of this type be thrown by the JVM.

Μ If you cannot determine the type of the exception object and the timing of the occurrence, you should take a system type exception object and be processed by the JVM.

Μ to the error caused by the application design errors, such as array bounds, illegal variables, and other types of exceptions, if you want to catch all types of exception objects, will increase the system overhead, resulting in inefficient program operation, it is recommended that the application can not capture such exceptions to the JVM to handle.

Μ for the implementation of input/output processing, network communication and database access functions of the code, the exception object must be captured and processed.

5. Starting with the JDK1.4 version, the Java language introduced an assertion (assert) mechanism.

Purpose: Program debugging (when testing code or debugging a program, always make assumptions that are used to capture these assumptions in code)

representation: An assertion is a statement in a program that checks for a Boolean expression (a correct program must guarantee that the Boolean expression evaluates to true; if the value is False, the program is already in an incorrect state, the system gives a warning or quits)

6. If there is no assertion mechanism, Java programs typically use IF-ELSE or switch statements for variable state checks. Disadvantages:

Μ because the data type being checked is not exactly the same, such statement forms are not uniform.

Μ because checking is only applied in the testing phase, and if-else or switch statements will still work after the release, if the elimination of the code means to annotate or delete the code, if the large amount of code that means that the workload is heavy and there are risks.

Advantages of using assertions:

Μ Java programmers deal with stateful inspection problems in a unified way;

The Μ assertion simply shuts down the feature when it is released.

7. Opening and closing of assertions

Μ is declared closed by default, so before using assertions, you need to turn on the assertion function by:
Java–eamyclass or
Java–enableassertions MyClass

Μ How to turn off assertion functionality:
Java–damyclass or
Java–disableassertions MyClass

Μ Note: Assertion checking is usually turned on during development and testing. To improve performance, the assertion check is usually turned off after the software is released.

8. Use of assertions

The keyword assert tag is used in Java, and the syntax format is:

Μ assert Expression1

when executing to an Assert statement, if the value of Expression1 is true, the program executes normally, and if the value is false, the statement creates a assertion error object and throws the object.

Μ assert Expression1:expression2

when an assertion fails, the system automatically passes the value of the Expression2 to the newly created Assertionerror object, which is then converted to a message string to save for more and more targeted checking for failure details.

Note: Both of these formats must be Boolean expressions

9. When to use assertions

Μ Generally, assertions are used to check for key values, and these values have a significant effect on the entire program, or on the completion of local functionality.

Μ assertion expressions should be short and understandable, and if you need to evaluate complex expressions, you should use function calculations.

Μ using Assertions

Check the control flow: in If-else and switch statements, you can add assert statements to a control tributary that should not occur. If this happens, the assert can be checked out.

U Check whether the input parameters are valid before the private method is evaluated
For some private methods, the input satisfies certain conditions and can be checked using assert at the beginning of the method, and for public methods, the assertion check is not usually used

Check that the method results are valid after the method is calculated

U Check Program invariants

Some programs have invariants, either a simple expression or a complex expression. The values of these invariants are invariant in the running declaration cycle of the program, and for some key invariants, they can be checked by assert.
Private Boolean isbalance () {
......
}//assert isbalance (): "Balance is destoried";

Throwableinstance is an object of thowable or thowable subclasses, and simple classes such as int, char, and non-throwable classes (such as String, Object) cannot be thow in statements.

The program terminates immediately after execution to the Thow statement, the following statement is no longer executed, and then in the try block containing it looks out for a catch clause that matches its type.

Java built-in run-time exceptions have two constructor methods, one with no parameters and one with a string parameter. When the second form is used, the parameter specifies a string that describes the exception. If the exception object is used as a parameter to print () or println (), the string is displayed.

If a method can cause an exception but is not prepared to handle it, you must specify some behavior so that the caller of the method can protect them, and to do this, you must include a throw clause in the method declaration. The throw clause usually lists all the exception types that a method might throw. This is important for all exceptions except the error, RuntimeException, and its subclasses. These other types of exceptions must be declared in the throw clause, and failure to do so will result in a compilation error.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.