Java exception (Exception) & Custom Exception __java

Source: Internet
Author: User
Tags exception handling finally block stack trace throw exception throwable

A Java exception architecture

Java.lang.Object
----java.lang.Throwable
--------Java.lang.Exception
------------java.lang.RuntimeException
--------Java.lang.Error
------------Java.lang.ThreadDeath


The Throwable class is a superclass of all errors or exceptions in the Java language. An object can be thrown through either a Java virtual machine or a Java throw statement only if it is an instance of this class (or one of its subclasses). Similarly, only one of this class or its subclasses can be a parameter type in a catch clause.
Instances of its two subclasses, Error and Exception, are typically used to indicate an exception condition. Typically, these instances are newly created in the context of an exception, and therefore contain related information, such as stack trace data.


The Exception class and its subclasses are a form of throwable that indicates the conditions that a reasonable application wants to capture, representing the exceptions that the program itself can handle.


Error is a subclass of Throwable that represents a serious error that cannot be recovered by the program itself, and is used to indicate a serious problem that a reasonable application should not attempt to catch.
During the execution of this method, it is not necessary to declare in the method any subclass of the Error that may be thrown but not captured, because the Java compiler does not check it, that is, when such an exception may occur in the program, even if it is not captured with the Try...catch statement, the Nor does it use the throws Word declaration to throw it, or it will compile through.


runtimeexception are superclass of exceptions that may be thrown during the normal operation of a Java virtual machine. The Java compiler does not check it, that is, when such an exception may occur in a program, even if it is not captured with the Try...catch statement, it is not thrown with a throws clause declaration, or it is compiled through, and this exception can be avoided by improving the code implementation.


Classification of exceptions
1. Non-run-time exceptions (Checked Exception)
Classes in Java that inherit from exception but do not inherit from RuntimeException are not run-time exceptions.
2. Run-time Exceptions (Runtime exception/unchecked Exception)
The RuntimeException class inherits directly from the exception class, which is called a Run-time exception. All run-time exceptions in Java are inherited directly or indirectly from the runtimeexception.


Two Java exception handling mechanism

1 Exception handling

1.1 There are two ways to deal with code that might appear to be abnormal:
1. To catch and handle an exception with a Try...catch statement in a method, the Catach statement can have more than one to match multiple exceptions. For example:

public void Test () {
	try{...
	} catch (IOException e) {
	  ...
	} catch (Exception e) {
	  ...
	} finally{...
	}
}

2. For exceptions that cannot be handled or to be transformed, an exception is thrown through the throws statement at the declaration of the method. For example:
public void Test () throws myexception{...
 if (...) {
  throw new myexception ();
 }


2.Tips:

2.1 If each method is simply throwing an exception, then in a multi-tiered nested call to the method invocation method, the Java virtual opportunity will look back from the method code block in which the exception occurred until it finds the code block that handles the exception. The exception is then handed over to the appropriate catch statement for processing. If the Java Virtual Machine traces the main () method at the bottom of the method call stack, if the code block that handles the exception is still not found, the following steps are followed:
1, call the exception of the object's Printstacktrace () method, print the method call stack exception information.
2. If the thread that has an exception is the primary, the entire program terminates, and if it is not the primary thread, the thread is terminated and other threads continue to run.

Through the analysis of thinking, we can see that the earlier processing of abnormal consumption of resources and time, the impact of the scope of the smaller. Therefore, do not throw the exception that you can handle to the caller.

2.2 There is one point that cannot be ignored: the code that must be executed in any case by the finally statement, which guarantees that some of the code must be executed in any case. For example, when a database query is abnormal, you should release the JDBC connection, and so on. The finally statement executes before the return statement, regardless of its position, or whether an exception is found in a try block. Finally, the only thing that is not executed is that the method executes the System.exit () method. The role of System.exit () is to terminate the currently running Java virtual machine. Finally, it is not possible to change the return value by assigning a new value to a variable, and it is also recommended that you do not use returning statements in a finally block, which makes no sense and can easily lead to errors.

2.3 Finally, you should also pay attention to the syntax rules for exception handling:
Try statements cannot exist alone, and catch, finally compose try...catch...finally, Try...catch, try...finally three structures, catch statements can have one or more, Finally statements are up to one, try, catch, finally these three keywords can not be used alone. The scope of the variables in try, catch, finally three blocks is independent and not accessible to each other. If you want to be accessible in three blocks, you need to define the variables outside the blocks. Multiple catch blocks, the Java Virtual Opportunity matches one of the exception classes or its subclasses, executes the catch block, and does not execute another catch block. Throw statements are not allowed to follow other statements, as these do not have the opportunity to execute. If a method calls another method that declares an exception, the method either handles the exception or the declaration is thrown.

The difference between 2.4 throw and throws keywords
Throw is used to throw an exception in the method body. The syntax format is: Throw exception object.
Throws is used to declare what exceptions the method might throw, after the method name, the syntax format is: throws exception type 1, exception type 2 ... Exception type N.


Three custom exceptions
Custom exceptions are usually defined as subclasses that inherit from the exception class. In general, we will inherit from the exception class directly, without inheriting a Run-time exception class.

3.1 Custom checked exceptions (Checked Exception)

1. Inherit exception, and cover the construction method

public class MyException extends exception{public
    myexception () {
        super ();
    }
    Public myexception (String msg) {
        super (msg);
    }
}

2. Use custom Exceptions in classes

public class Exceptiontest {public


    static void execute (String a) throws MyException {
        System.out.println (" Execute ... ");
        if ("true". Equals (a)) {
            throw new myexception (argument cannot be true);}}


3.2 Custom Run-time Exceptions

1. Inherit from RuntimeException

The public class Myrtexception extends RuntimeException {    //or inherits any standard exception class
    /**
	 * */
	private static final Long serialversionuid = 1L;
	
	Public myrtexception () {	//used to create a parameterless object
		
	} public                
	
    myrtexception (String message) {        //To create the specified Parameter object
        Super (message);                             Call Superclass Builder
    }
    
}

2. Use custom Exceptions in classes

public class Exceptiontest {public

    static void execute (String a) {
        System.out.println ("Execute ...");
        if ("true". Equals (a)) {
            throw new myrtexception (argument cannot be true);}}


Note: RuntimeException are superclass of exceptions that may be thrown during the normal operation of a Java virtual machine. No subclasses of RuntimeException need to be declared in the throws clause.

Four abnormal transitions and abnormal chains
Abnormal transformation is actually to catch an exception, the exception to the new type of exception thrown again, this is generally for the exception of information more intuitive, such as:

public void Run () throws myexception{...
 try{...
 } catch (IOException e) {
  ...
  throw new MyException ();
 } finally{...
 }
}


Abnormal chain, in later versions of JDK1.4, the Throwable class supports the exception chain mechanism. Throwable contains a snapshot of the thread execution stack when its thread was created. It also contains a message string giving more information about the error. Finally, it can also contain cause (reason): Another throwable that causes this throwable to be thrown. It is also called an anomaly chain facility, because cause itself will have cause, and so on, forming an anomaly chain, each of which is caused by another exception.
In layman's parlance, the exception chain is the original exception packaging as a new exception class, and in the new exception class encapsulated the original exception class, this is done to find the root cause of the exception.
You can create a custom exception type that contains the cause of an exception by using the two constructed methods of Throwable:

Throwable (String message, throwable cause)
Constructs a new throwable with the specified detail message and cause.
Throwable (Throwable cause)
Constructs a new throwable with detailed messages with the specified cause and (cause==null. null:cause.toString ()), which typically contains detailed messages for classes and cause.


The Getcause () method returns the cause of this throwable, or null if cause does not exist or is unknown.
Initcause (Throwable cause) Initializes the cause of this throwable to the specified value.

In the Throwable subclass exception, there are similar construction methods that specify the cause of the exception:
Exception (String message, throwable cause)
Constructs a new exception that specifies detailed messages and causes.
Exception (Throwable cause)
Constructs a new exception based on the specified reason and the detailed message (Cause==null. null:cause.toString ()) (it typically contains cause class and verbose messages).

Therefore, you can construct a new exception class with an exception reason by extending the exception class.

Five Java exception handling principles and techniques
Avoid too large try blocks, and do not place the exception code in the try block, keeping one try block corresponding to one or more exceptions. Refine the type of the exception, regardless of what type of exception is written as Excetpion. Catch blocks try to keep a block to catch a class of exceptions, do not ignore the caught exception, and then either process it, translate it, or throw back the new type of exception. Don't throw away the exceptions you can handle. Do not use Try...catch to participate in the program process, the basic purpose of exception control is to deal with the abnormal situation of programs.





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.