Java Exception Handling

Source: Internet
Author: User
Tags throw exception throwable

I. Overview

If a person is sick, we have to diagnose it, and then the right remedy, or let the disease continue to develop or a variety of diseases at the same time, this person will become painful, can not work properly. Similarly, Java is running in the network, in order to ensure the operation of security, the network can operate normally, the same needs to find out the program runtime errors, and can be processed in a timely and efficient manner, Java leads to the exception. The so-called exception is different from the normal, then we can also call it an exception.

Second, the anomaly framework

Exception handling is very important in program design, is a difficulty in programming, when we learn C + +, the same exception or error if more than one place, then we must every place to do the same treatment, it feels rather troublesome. Java language Design When considering this problem, the exception processing framework, all the exceptions can be represented by a type, different types of exceptions corresponding to different subclass exceptions, defines the exception handling specification. The exception chain mechanism was added after the 1.4 release, making it easy to track exceptions.

Throwable is a class in the class library Java.lang package that derives two subclasses: Error and exception.

Throwable can be thrown, as long as any class that inherits it is thrown.

1, Error: system Internal errors, is the program can not handle the error.

It represents a more serious problem when running an application. Most errors are not related to the operations of the Code writer, which are not available, they are outside the control and processing power of the application, and represent problems with the JVM when the code is running. For example, a Java virtual machine runs an error and OutOfMemoryError occurs when the JVM no longer has the memory resources needed to continue the operation. When these exceptions occur, the Java virtual machine typically chooses to terminate the thread.

2, Exception: The program itself can handle the exception.

Exception include: run-time exception errors and non-runtime exceptions (compilation exceptions).

(1) Run-time exception (can be checked exception): The Java compiler does not check it, that is, when this kind of exception can occur in the program, even if it is not captured with the Try-catch statement, and does not use the throws clause declaration to throw it, also compiled through. Includes RuntimeException and its subclasses. These exceptions are usually caused by procedural logic errors, and the program should avoid this kind of exception as much as possible from a logical point of view.

(2) Non-runtime exception (exception not checked): The Java compiler checks it, that is, when such exceptions may occur in the program, to catch it with the Try-catch statement, or to throw it with the throws clause declaration, or the compilation does not pass. Includes classes other than RuntimeException.

Add: The exception that can be checked is that the compiler requires an exception that must be disposed: The exception that is not checked is the compiler does not require a forced disposition of the exception, it also includes errors (error).

Exception, like other classes, has its own properties and methods to understand that it facilitates our better user-definable exception classes.

Its two constructors are

public Exception ();

Public Exception (String s);

Its common approach is to

Public stringtostring ()//This method is used to give detailed error information

Public voidprintstacktrace ()//print out the stack usage trajectory of the current exception object, that is, the program executes the methods of those objects or classes, so that the exception object is generated during the run.

Summary: The most important difference between errors and exceptions: Exceptions can be handled by the program itself, and errors cannot be.

Iii. Definition of exceptions

1, system-defined operation exception: the system is defined in advance and packaged in the Java class Library. It usually corresponds to a system run error, which is likely to cause operating system errors or even the entire system to be paralyzed, so define special classes to handle. Common system-defined exceptions can be found in http://soft.chinabyte.com/database/491/12129991.shtml, the blogger's Good Housekeeping.

2, user-defined exception: is the programmer according to the special logic of the program in the user program to create their own user-defined exception classes and exception objects. This user-defined exception is primarily used to handle specific logic run errors in the user program.

The following defines an outbound method for the queue class, which is only part of the code:

Class Queue{int dequeue ()  //minus team operation, if the queue is not empty, a data {int data is fetched from the head of the queue,    if (!isempty ()) {Data    = First.getdata (); First=first.getnext (); return;} else{     Return-1}}}

In this method, if the queue is already empty, then this method gives a data "1" indicates that the operation of the team failed, so the disadvantage of the deal is not to save "1" this data, but also require other calls Dequeue method to understand the exception of the Convention, obviously to the program debugging and operation are inconvenient, To solve this problem, you can define a program exception emptyqueueexception, which specifically deals with logic errors that are "out of line in the empty queue."

Class Emptyqueueexception extends Exception     //subclass of user-defined system class {queue queue;    Public emptyqueueexception (Queue Q) {    super ("Queues are empty! "); queue = q;} Public String toString () {         ///Overloads the parent class method, giving the detailed error message           return ("queue" + queue.tostring () + "is already empty, the execution of the team operation throws an exception!) ");}}

Four, throw the exception

If a Java program throws a recognizable error at run time, it produces an exception class object corresponding to the error, which is called an exception throw.

1, the system automatically throws the exception: system-defined exceptions can be automatically thrown by the system. For example, an arithmetic exception that occurs when the divisor is zero.

2. Exception thrown by statement

User-defined exceptions cannot be thrown by the system and must be backed by a throw statement. And the new object of the exception class should be thrown if the exception exception type is thrown, then the method is declared to throw all exceptions. Multiple exceptions can be separated using commas. The syntax format for the throws statement is:

MethodName throws Exception1,exception2,.., exceptionn {...    Thrownew exception class name;    ... } ;

The following code shows how we throw the above queue () method may throw Emptyqueueexpection exception object

Class Queue{int Dequeue () throws Emptyqueneexception  //minus team operation, if the queue is not empty, a data {int data is fetched from the head of the queue,    if (!isempty ()) {    data = First.getdata (); First=first.getnext (); return;} else{     Throw (new Emptyqueueexception (This));}}}

Throw Exception Considerations:

1, the overriding method needs to throw the same as the exception type thrown by the original method or does not throw an exception;

2, you must declare the method can be thrown any can be found exception (checked exception). That is, if a method may appear to be subject to a try-catch, either by the use of a statement, or by a throws clause declaration to throw it, or cause a compilation error

3, in the programming can not throw an exception in main, to be processed in the Main method

V. Exception handling

When we throw an exception, we need to handle the exception. Exception handling mainly includes catching exceptions, jumping of program flow and definition of exception-handling block.

Format of exception handling:

try{   ////The program code that may occur}catch{  //captures and handles the type of exception thrown by the try, can have multiple Catch statements}finally{  //Handle the state of the program uniformly}

For the above example, do exception handling, the code is as follows:

public class Test{public static void Main (String args[]) {   queue queue = new Queue ();   for (ing i=1;i<8;i++)   {   queue.enqueue (i);   Call queue's queued function   System.out.println (Queue.visitallnode ());//Display the contents of the queue   }   try {while  (! Queue.isempty ())   //Call out Team function  {  System.out.print (queue.dequeue () + "Out");              System.out.print (" There are "+ Queue.visitallnode ()) in the queue;}   }   catch (emptyqueueexception Eqe)   {   System.out.println (eqe.tostring ());}}}   

For multi-exception processing, is to define a number of blocks to implement, each block to receive and process a specific exception object, and the exception type of small before, big put, often error before put, not often error put back, because the catch is in order. If all catch blocks do not match the current exception object, the current method cannot handle the exception object, the program flow returns to the upper method that calls the method, and if the upper method defines a catch block that matches the resulting exception object, the process goes to the catch Or continue backtracking, as shown:

The principle of exception handling:

1, avoid too large try block, do not put the code will not appear in the try block, try to keep a try block corresponding to one or more exceptions.

2, refine the type of the exception, not regardless of what type of exception are written excetpion.

3, catch block as far as possible to keep a block catch a class of exceptions, do not ignore the caught exception, capture to either process, or translate, or re-throw the new type of exception.

4, do not use Try...catch to participate in control procedures, the fundamental purpose of exception control is to deal with the abnormal situation of the program.

Vi. Summary

In short, the program execution often occurs in addition to 0 overflow, the array out of bounds and other running errors, affecting the normal execution of the program. Errors and anomalies are unavoidable, and a good application, while satisfying the various functions required by the user, should have the ability to anticipate the various anomalies that may arise during the execution of the program, and to properly handle the anomalies. The Java language addresses runtime errors through an object-oriented exception handling mechanism, which prevents unexpected results caused by incorrect program code or system errors. Reduce the programmer's work, increase the flexibility of the program, increase the readability and robustness of the program.


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.