Java violation control summary

Source: Internet
Author: User
Java violation control summary

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.

Violation class hierarchy
Violation class hierarchy
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

/**

* <p>Title:Except1.java </p>

* <p>Description: Tested using JDK1.4.0 under Win2000 Professional</p>

* @author Mac

* @version 2002/9/9

*/

import java.lang.Thread;

class Except1

{

public static void main(String[] args)

{

    Except1 obj = new Except1();

    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 Except1

In the above example, we can see that the mymethod method simply declares that it will generate a violation called interruptedexception (throws interruptedexception ), the actual handling of the violation is delayed in the main method (catch (interruptedexception E. Run this example and answer the following questions to see if you have mastered it.

1. What will happen if all the violation control code is removed? Follow the prompts to improve your program step by step.

2. How is the violation in method mymethod caused? What about the main method?

3. Can I change catch (interruptedexception E) to catch (exception e? Why?

Capture multiple violations

In addition, you can capture multiple violation types in the try code block and control each type separately. Each type corresponds to an independent catch clause:

   try

    {

        //codes that might throw exceptions

}

catch(ExceptionType1 e1)

{

    //actions do with e1

}

catch(ExceptionType2 e2)

{

    //actions do with e2

}

catch(ExceptionType3 e3)

{

    //actions do with e3

}

// …

Declare multiple violations
You can capture multiple violations. Of course, you can declare multiple violations. For example, in the mymethod method, four violations can be declared simultaneously:

 void myMethod() throws

                    InterruptedException,MyException,HerException,OurException

    {

        //method code

}

Finally clause
As we have already said, the content in the finally clause will be executed, whether or not any violation occurs. We can use this feature to place some code in the finally clause to execute functions such as resource recovery and memory release.

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.