Exception Handling in Java

Source: Internet
Author: User

 

Exception Handling in Java

1. Hierarchy of exception classes

Java. Lang. Object

Java. Lang. throwable

Java. Lang. Exception

Java. Lang. runtimeexception

...

Java. Lang. Error

Java. Lang. threaddeath

Java. Lang. virtualmachineerror

...

  

1. throwable

The throwable class is a superclass of all errors or exceptions in the Java language. Only when an object is an instance of this type (or its subclass) can it be thrown through a Java virtual machine or Java throw statement. Similarly, only this class or its subclass can be the parameter type in the catch clause.

Two subclass instances: Error and exception, which are usually used to indicate exceptions. Generally, these instances are newly created in the context of an exception and contain relevant information (such as stack trace data ).

2. Exception

The exception class and its subclass are a form of throwable. It specifies the conditions that a reasonable application wants to capture, indicating the exceptions that the program itself can handle.

3. Error

An error is a subclass of throwable, indicating a serious error that cannot be recovered by the program itself. It is used to indicate that a reasonable application should not try to capture a serious problem.

During the execution of this method, you do not need to declare any subclass of an error that may be thrown but not captured through throws in the method, because the Java compiler does not check it, that is, when such exceptions may occur in the program, even if try... catch statements capture it, and throws statements are not used to declare whether to throw it or compile it.

4. runtimeexception

Runtimeexception is a subclass of exception, which is a super class that may throw exceptions during the normal operation of the Java Virtual Machine. The Java compiler does not check it, that is, when such exceptions may occur in the program, even if try... catch statements capture it, and throws statements are not used to declare whether to throw it or compile it. This exception can be avoided by improving code implementation.

5. threaddeath

Threaddeath is a subclass of error. When the stop method with zero parameters in the Thread class is called, the affected thread will throw a threaddeath instance.

The instance of this class should be captured only when the application must be cleared after the asynchronous termination. If threaddeath is captured by a method, it is very important to throw it again, because in this way, the thread can be truly terminated.

 

Ii. runtime exceptions and checked exceptions

There are two types of exceptions: runtime exceptions and checked exceptions.

1. runtime exception

This means that there are bugs in the program, such as array out-of-bounds, 0 division, input parameters do not meet the specifications... such exceptions need to be modified to avoid. When this type of exception may occur in the program, even if the try... catch statement is not used to capture it, throws statements are not used to declare it and the program will still be compiled. For example, if the divisor is zero, a java. Lang. arithmeticexception exception is thrown.

2. Check for exceptions

The program is correct, but the external environment conditions are not met. For example: user errors and I/O problems-the Program tries to open a remote socket port that does not exist. This is not a logic error of the program itself, but probably a remote machine name error (User spelling error ). For commercial software systems, program developers must consider and handle this issue. The Java compiler enforces the processing of such exceptions. If such exceptions are not caught, the program cannot be compiled.

3. Differences between the two

An exception during running indicates that the program cannot be resumed. The cause of this exception is generally due to an incorrect operation. Once an error occurs, we recommend that you terminate the program.

Checked exceptions indicate exceptions that can be processed by the program. If the method that throws an exception does not process it or cannot process it, the caller of the method must handle the exception. Otherwise, the call will fail and compilation will fail. Of course, these two exceptions can be captured and handled by a program, such as running exceptions with Zero Divisor:

4. runtime error

The error class and its subclass indicate runtime errors, which are usually thrown by the Java Virtual Machine. JDK defines some error classes, such as virtualmachineerror and outofmemoryerror, which cannot be fixed by the program itself. generally, the error class is not extended to create custom error classes. The runtimeexception class indicates errors in the program code, which can be extended. You can create exception classes at specific runtime.

Errors (runtime errors) and runtime exceptions are the same: the Java compiler does not check them and stops running when they occur during the program running.

5. Best Solution

For runtime exceptions, do not use try... catch is used to capture and handle the exception. In the program development and debugging stage, try to avoid this exception. Once this exception is found, the correct method will improve the Code and implementation method of the program design, modify errors in the program to avoid such exceptions. Capturing and handling runtime exceptions is a good solution, because you can avoid this exception by improving the code implementation.

For checked exceptions, if they are not mentioned, they will be handled in a down-to-earth manner, either captured and resolved using try... catch or throws!

For errors (runtime errors), no processing is required in the program,The problem should be found outside the program and solved.

 

Iii. syntax rules for exception handling:

1. Try statements cannot exist independently. They can be used with catch and finally to form try... catch... finally, try... catch, try... three finally structures: one or more catch statements and one finally statement. The three keywords try, catch, and finally cannot be used separately.

2. variables in the try, catch, and finally code blocks are independent of each other and cannot access each other. If you want to access all three blocks, you need to define the variables outside these blocks.

3. When multiple catch blocks match one of the exception classes or their subclasses, the Java virtual machine executes the Catch Block instead of other catch blocks.

4. Throw statements cannot be followed by other statements because they are not executed.

5. If a method calls another method that declares to throw an exception, the method either handles the exception or declares to throw the exception.

6. Difference Between throw and throws keywords:

Throw is used to throw an exception in the method body. Syntax format: Throw exception object.

Throws is used to declare what exceptions A method may throw. After the method name, the syntax format is: throws exception Type 1, exception type 2... exception type N.

 

Iv. Custom exceptions

Create an exception or runtimeexception subclass to obtain a custom exception class. For example:

 

Public classMyexception
ExtendsException {

PublicMyexception (){}

PublicMyexception (string SMG ){

Super(SMG);

}

}

 

V. Abnormal transformation and exception chain

An exception transformation is actually to throw an exception with a new type after an exception is caught. This is generally to make the exception information more intuitive!

The exception chain encapsulates the original exception as a new exception class and encapsulates the original exception class in the new exception class. This aims to find the root cause of the exception.

Two constructor functions are supported:

Throwable (string message, throwable cause)

Throwable (throwable cause)

Methods to obtain the original exception class:

Getcause (): return the cause of the throwable. If the cause does not exist or is unknown, null is returned.

 

For example:

PrivatevoidRun ()Throws
Myexception{

Try{

//...

}Catch(Ioexception e ){

//...

ThrownewMyexception(E );

}Finally{

//...

}

}

 

6. Principles and skills of Java Exception Handling

1. Avoid too large try blocks. Do not place codes that do not encounter exceptions in try blocks. Try to keep one or more exceptions corresponding to one try block.

2. Refine the exception type. Do not write excetpion whatever type of exception.

3. Try to keep a catch exception for a block. Do not ignore the caught exception. After capturing the exception, either process it, translate it, or throw a new type of exception.

4. Do not throw exceptions that you can handle to others.

5. Do not use try... catch to control the program process. The fundamental purpose of exception Control is to handle abnormal conditions of the program.

 

 

 

 

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.