Java exception Handling mechanism--summary

Source: Internet
Author: User
Tags array length finally block instance method throw exception try catch

1. The following is a basic description of the exception: Java exception hierarchy diagram as follows

Throwable: There are two important subclasses: Exception (Exceptions) and error (Error), both of which are important subclasses of Java exception handling, each of which contains a large number of subclasses, such as (the subclass exception in the structure diagram above is not all, Only some of the most important common exceptions are noted.)

Error (Error): A bug that the program cannot handle , indicating a more serious problem in running the application.

Most errors are unrelated to what the code writer does, and represent a problem with the JVM (the Java virtual machine) that is running the code. For example, Java Virtual machine run error (VIRTUALMACHINEERROR), outofmemoryerror occurs when the JVM no longer has the memory resources required to continue the operation. When these exceptions occur, the Java Virtual machine (JVM) typically chooses to terminate the thread. These errors are not available because they are outside the control and processing power of the application and are mostly not allowed when the program is running. For a well-designed application, even if it does, it should not be an attempt to deal with the anomalies that it causes.

Exception (Exception): is an exception that the program itself can handle .

The Exception class has an important subclass runtimeexception. The RuntimeException class and its subclasses represent errors thrown by the JVM common operation. For example, if you attempt to use null object references, divide by zero, or array out of bounds, the run-time exceptions (NullPointerException, ArithmeticException), and arrayindexoutofboundexception are raised respectively.

2. Handling of exceptions

In Java, if a method throws an exception, it can either be snapped in the current method, then handle the exception, or the exception can be thrown up and handled by the method caller.

  A>. Java's exception capture structure consists of try, cache, and Finally3 parts , for example:

1 Try {2     //blocks of code that may throw exceptions3     intresult = 2/0;4System.out.print ("Result of operation:" +result);5}Catch(ArithmeticException e) {6     //handling of Exception 17System.out.print ("An arithmetic exception has occurred");8}Catch(Exception e) {9     //handling of Exception 2Ten     //And so can also add a variety of exception processing, by the structure, exception is the runtime exception of the parent class, so all exceptions can be exception receive, in general, if there is no specific exception to the special handling catch write exception can be  OneE.printstacktrace ();//to print stack information for an exception A}finally { -     //Program code block--part of the exception handling structure last processed -}

  Try statement block: used to execute code blocks that may have exceptions. You can then pick up 0 or more catch blocks, and if there is no catch block, you must follow a finally block.

Catch statement block: a try catch structure can have multiple catch, catch different exceptions to do different exception handling, no special needs, generally with a exception can be

PS: When multiple catch, the parent exception must be written in the following-refer to the exception structure diagram, such as the above code snippet, the Exception and arithmeticexception exchange position, Exception in front, by the anomaly structure diagram, Exception is the parent of arithmeticexception, so there is an arithmetic exception, exception can also catch the exception, after the addition of ArithmeticException has no use, and therefore will be directly compiled error.

  FINALLY statement block: a try catch struct in which finally can be written and not written, when there is a finally statement block, it means that the code block will be executed regardless of whether there is an exception, usually used in the input stream, the output stream closed.

  Note: The interview is often asked where: if there is a return,finally in the try is executed. Answer: The finally statement block is still executed, before the return in the TRY statement block

  The following 4 special cases finally do not execute:

      • An exception occurred in the finally statement block
      • Use System.exit () to exit the program in the previous code
      • program died on the thread
      • Shutting down the CPU

  B>. throws,throw

An exception may occur in a method, but you do not want to handle the exception in the current method, you can use throws, and thethrow keyword throws an exception in the method.

  The throws keyword is typically applied when declaring a method to specify an exception that the method might throw (multiple exceptions can be separated by commas) with the following syntax:

1  Public Static voidMain (string[] args) {2     Try{3 test ();4}Catch(ArithmeticException e) {5System.out.print ("Test () method throws an arithmetic exception");6     }7 }8     9  Public Static voidTest ()throwsarithmeticexception{Ten     intresult = 3/0; One}

After throwing an exception to the upper level using the throws keyword, if you do not want to handle the exception, you can continue to throw up, but ultimately it is up to the code that can handle the exception.

The throw keyword is typically used in the method body and throws an exception object. when the program executes to the throw statement, it terminates immediately, and the statements following it are not executed.

 C>. Custom exceptions

Use the Java built-in exception class to describe most of the exceptions that occur during programming. In addition, users simply inherit the exception class to customize the exception class.

The use of custom exception classes in your program can be broadly divided into the following steps.
(1) Create a custom exception class.
(2) throws the exception object through the Throw keyword in the method.
(3) If the exception is handled in the method that currently throws the exception, it can be captured and processed using the Try-catch statement, otherwise the exception that is thrown to the method caller is indicated by the throws keyword at the declaration of the method, and proceed to the next step.
(4) Catch and handle exceptions in the caller of the exception method.

3. Common exception classes

  • NullPointerException NULL pointer exception. This exception is thrown when an app tries to use null where the object is required. For example: Call an instance method of a Null object, access the properties of a null object, evaluate the length of a null object, throw null with a throw statement, and so on.
  • ClassCastException Type Conversion exception
  • ClassNotFoundException the corresponding class exception was not found
  • ArithmeticException arithmetic anomalies
  • ArrayIndexOutOfBoundsException array index out-of-bounds exception
  • Arraystoreexception an exception that is thrown in an array that contains incompatible values
  • SQLException Manipulating Database Exception classes
  • nosuchfieldexception Field not found exception
  • The Nosuchmethodexception method did not find the thrown exception

  • NumberFormatException string conversion to a number thrown exception
  • Negativearraysizeexception array length is a negative exception
  • Stringindexoutofboundsexception string index out of range throw exception
  • IOException exceptions that may occur when manipulating input and output streams
  • IllegalArgumentException Illegal parameter exception
  • Instantiationexception when an application attempts to create an instance of a class using the Newinstance () method in the class classes, and the specified class object cannot be instantiated, the exception is thrown
  • Arraystoreexception an exception that is thrown in an array that contains incompatible values
  • SecurityException Security exception
  • Eofexception file has ended exception
  • FileNotFoundException File not found exception
  • NumberFormatException string conversion to a number thrown exception
  • Illegalaccessexception does not allow access to a class of exceptions

Java exception Handling mechanism--summary

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.