Java violation Control

Source: Internet
Author: User

 


Preface

This article mainly discusses Java's violation control, including the following:

1) What is violation control?

2) concept of violation

3) class hierarchy in Java

4) how to throw and capture violations

5) how to handle the violation after capturing

This article will go into the above details to show you the full picture of Java violations, so that you can easily handle various possible situations in future programming.

What is violation control?
To put it simply, violation control provides you with the following capabilities in a program:

1) monitor exceptions in the program

2) When an exception occurs, give control to your own violation control code.

Violation Control Process
In Java, these tasks are completed by the following keywords: try, catch, throw, throws, and finally. Their basic code structure is as follows:

Try
{
// Code block
}
Catch (ExceptionType e)
{
// Control code for this violation type
} Finally
{
// Clear collection and other tasks
}

First, execute the code block contained in the try. If an execution error occurs, the program throws a specific type of violation and you capture the violation and then execute the violation control code in the catch. Finally, code in finally must be executed no matter whether the program generates any violation. It mainly involves variable clearing and Resource Recycling (1.
First, let's take a look at the Throwable class. Sun describes it like this:

The Throwable class is the superclass of all errors and exceptions in the Java language. only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. similarly, only this class or one of its subclasses can be the argument type in a catch clause.

Instances of two subclasses, Error and Exception, are conventionally used to indicate that exceptional situations have occurred. typically, these instances are freshly created in the context of the specified tional situation so as to include relevant information (such as stack trace data ).

We can see that:

1) in Java, the violation object must be an instance of a class derived from Throwable.

2) Throwable contains two direct subclasses: Error and Exception ).

3) We can create our own violation class, as long as it is derived from Throwable or its subclass (specifically, it should be derived from Exception or its subclass, this article will not discuss in detail how to create your own violation classes. You can refer to the relevant materials ).

Error and Exception
Error indicates serious errors caused by exceptions. We should not capture such objects, including internal system errors and resource depletion. The Exception class indicates the situations that you must capture and process.

Checked Exceptions and Unchecked Exceptions)
There is a very important class in the subclass of Exception: RuntimeException (2 ). Any violation derived from it or its subclass in Java is called "Unchecked Exceptions ), any violation derived from other Exception classes is called "Checked Exceptions" (3 ).

The main problems involved in non-checking violations include: styling errors, array out-of-bounds access, and NULL pointer access. These problems are generally caused by your programming. Simply put, a non-check violation is a violation that is checked by the compiler without being controlled by your program. Check violation refers to the violation that you must handle. Otherwise, a compilation error is generated during compilation. You can choose any of the following methods to handle it:

1) Capture violation: the catch code block is followed by the try code block.

2) Declaration violation: throws can be used in the method signature to notify users of possible violations.

Constructors and methods of the Throwable class
As we have mentioned above, throwable is a superclass for all violations. Here we will analyze it. The Throwable class has four constructor methods:

Throwable ()

Throwable (String message)

Throwable (String message, Throwable cause)

Throwable (Throwable cause)

The last two methods are newly introduced in JDK1.4 to support the so-called chained exception mechanism (4 ). Next, let's take a look at some of the main methods of throwable:

FillInStackTrace ()

GetStackTrace ()

PrintStackTrace ()

SetStackTrace (StackTraceElement [] stackTrace)

These four methods are used to process StackTrace. If you are not familiar with StackTrace, you can understand it as follows: it is what you see on the screen when the program is terminated due to a running error.

GetLocalizedMessage ()

GetMessage ()

These two methods provide interfaces for accessing messages encapsulated in the object in violation.

ToString ()

Throwable reloads the toString method of the Object class to return a brief description of Throwable.

All the object in violation inherits the above methods of the throwable class, so you can call any of the methods in the catch code block. For example, you can use the getMessage method to display detailed information about the violation.

So what does the violation mean?


Here we reference The original words of Campione and Walrath in The Java Tutorial (5:

The term exception is shorthand for the phrase "exceptional event ". it can be defined as follows: Definition: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions."

Every time an exception occurs in a method, it instantiates a violation object and gives control to the runtime system for processing, these tasks are all done by throw (that is, we usually call throwing an violation ). In addition, the object contains information such as its type and program status when the violation occurs.

Handle Violation
It can be seen from the above that the runtime system is responsible for identifying the code for handling the violation.

After each violation occurs, the system starts to search for the appropriate violation controller (catch code block) at runtime. The comparison criteria are as follows: the violation type in the violation controller must be the generated violation type or its superclass. If no appropriate controller is found until the end of the program, the program is automatically terminated.

Advantages of violation Control
Compared with the traditional error handling mechanism, violation control has the following advantages:

1) Separate the error handling code from the general code

2) Handing errors over to the call stack for processing. This is the so-called idea of "handing over things to the most appropriate person to accomplish things ".

3) by classifying the violation, we can easily see the cause and cause of the error.

More details about violation Control
As we have mentioned earlier, except for the violation exceptions derived from the Error and RuntimeException classes, you must control (handle) or declare (declare) All the violations that may be thrown in the program, that is, all check violations must be handled. Otherwise, the compiler will light up the red light on you and refuse to compile.

Capture Violation
Selecting capture violation means that your program must have a catch block, and the type of the ExceptionType parameter must be the type of the thrown violation, or supperclass in a certain inheritance chain) (6 ).

Declare Violation
If a check violation is generated in the method, but you do not provide the violation control in this method, you must declare that this method may throw a specific violation, you can use the keyword throws to achieve this goal. The syntax structure is (only the signature part of the method is listed ):

MethodName (paramType param) throws ExceptionType

What violations will be thrown in the method?

It includes the code throwing violation in your method, the throwing violation of the method you call, and even the throwing violation of other methods called in the method you call. In short, as long as the control flow is still within the scope of your method, you must consider all the throwing violations.

Instance code

/**

*

Title: javast1.java



*

Description: Tested using JDK1.4.0 under Win2000 Professional



* @ Author Mac

* @ Version 2002/9/9

*/
Import java. lang. Thread;
Class required T1
{
Public static void main (String [] args)
{
Required T1 obj = new required T1 ();
Try
{// Begin try block
Obj. myMethod ();
}
Catch (InterruptedException e)
{
System. err. println ("Handle exception here ");
} // End catch block
} // End main

Void myMethod () throws InterruptedException
{
Thread. currentThread (). sleep (1000 );
} // End myMethod
} // End class skip T1

In the above example, we can see that the myMethod method simply declares that it will generate an violation called InterruptedException (throws InterruptedException

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.