About exception Exceptions in Java

Source: Internet
Author: User
Tags arithmetic class definition instance method thread class throwable

I. Concepts of understanding anomalies and handling exceptions

An exception is an abnormal event that occurs during the course of a program's operation, and it interrupts a running program.

Exception is not an error

The key position in the program has exception handling, which improves the stability of the program.

Second, mastering the Java exception handling mechanism

Java exception handling is implemented by 5 keywords

Try: Trying to put the code where the error is likely to occur and must have

Catch: Capture, executed when an exception occurs

Finally: Eventually, regardless of whether an exception is performed

Throw: Throws, throws an exception

Throws: Throws more than one, declares that the method will produce some exceptions

III. classification and class structure of Java exceptions

Some common exceptions are built into the Java Standard library, which take throwable as the top-level parent class.

Throwable also derives the error class and the exception class.

Error: An instance of the error class and his subclass represents the JVM's own error. Errors cannot be handled by programmers through code, and error rarely occurs. Therefore, programmers should focus on the various exception classes under the branch of the parent class exception.

Exceptions: Exception and his subclasses represent a variety of unexpected events that are sent when the program is run. Can be used by the Java exception handling mechanism, which is the core of exception handling.

Iv. Some common Java exception collations
Arithmetic Exception class: Arithmeticexecption NULL pointer exception class: NullPointerException type cast exception: classcastexception array negative subscript exception: Negativearrayexception array subscript out of bounds exception: ARR Ayindexoutofboundsexception violation of security principle exception: Secturityexception file ended exception: Eofexception file not Found exception: FileNotFoundException string converted to numeric exception: NumberF Ormatexception Operation Database Exception: SqlException input and Output exception: IOException method not found exception: Nosuchmethodexception Java.lang.AbstractMethodError Abstract method Error. Thrown when an application tries to invoke an abstract method. Java.lang.AssertionError assertion is wrong. Used to indicate a condition in which an assertion failed. Java.lang.ClassCircularityError class cyclic dependency error. When a class is initialized, the exception is thrown if a circular dependency between the classes is detected. Java.lang.ClassFormatError class format error. Thrown when a Java virtual machine attempts to read a Java class from a file and detects that the contents of the file do not conform to the valid format of the class. Java.lang.Error error. is the base class for all errors that identify serious program run issues. These problems often describe anomalies that should not be captured by the application. Java.lang.ExceptionInInitializerError Initialization program error. Thrown when an exception occurs during the execution of a static initializer for a class. Static initializers refer to static statement segments that are included directly in the class. Java.lang.IllegalAccessError illegal access error. This exception is thrown when an application attempts to access, modify, or invoke the domain (field) of a class or call its methods, but violate the visibility declaration of a domain or method. Java.lang.IncompatibleClassChangeError incompatible class change error. This exception is thrown when an incompatible change is made to the class definition on which the method being executed depends. This error is easily thrown when you modify the declaration definition for some classes in your app without recompiling the entire application. Java.lang.InstantiationError instantiation of the error. When an application tries to pass Java's new operatorThrows the exception when constructing an abstract class or interface. Java.lang.InternalError internal error. Used to indicate an internal error occurred with the Java virtual machine. Java.lang.LinkageError link error. The error and all its subclasses indicate that a class depends on another class, and after that class is compiled, the dependent class changes its class definition without recompiling all of the classes, which in turn raises the error condition. Java.lang.NoClassDefFoundError class definition error not found. This error is thrown when a Java virtual machine or class loader attempts to instantiate a class and cannot find the definition of the class. There is no error in the Java.lang.NoSuchFieldError domain. This error is thrown when an application attempts to access or modify a domain of a class that does not have a definition of that domain in the definition of that class. The Java.lang.NoSuchMethodError method has no errors. This error is thrown when an application attempts to invoke a method of a class that does not have the definition of the method in the definition of the class. Java.lang.OutOfMemoryError Insufficient memory error. This error is thrown when the available memory is insufficient for a Java virtual machine to be assigned to an object. Java.lang.StackOverflowError Stack Overflow error. This error is thrown when the hierarchy of an application recursive call is too deep to cause a stack overflow. Java.lang.ThreadDeath thread ends. This error is thrown when the stop method of the thread class is called to indicate the end of the thread. Java.lang.UnknownError unknown error. Used to indicate a situation in which a Java virtual machine has an unknown critical error. Java.lang.UnsatisfiedLinkError an unsatisfied link error. Thrown when a Java virtual machine does not find a class that is declared as a native language definition of the native method. Java.lang.UnsupportedClassVersionError Unsupported class version error. This error is thrown when the Java Virtual machine attempts to read a class file, but discovers that the primary and minor version number of the file is not supported by the current Java virtual machine. Java.lang.VerifyError validation error. This error is thrown when the validator detects an internal incompatibility or security issue in a class file. Java.lang.VirtualMachineError Virtual machine error. A condition that indicates that the virtual machine is compromised or that the resource required to continue performing the operation is insufficient. Java.lang.ArithmeticException arithmetic condition is abnormal. For example: integers except 0. Java.lang.ArrayIndexOutOfBoundsExceptIon array index out of bounds exception. Thrown when the index value of an array is negative or greater than or equal to the size of the arrays. Java.lang.ArrayStoreException array Storage exception. Thrown when a non-array declaration type object is placed into the array. Java.lang.ClassCastException class modeling anomalies. Assuming that there are classes A and B (A is not a parent or subclass of B), and O is an instance of a, the exception is thrown when an O is forced to be constructed as an instance of Class B. This exception is often called coercion type conversion exception. Java.lang.ClassNotFoundException The class exception was not found. This exception is thrown when an application attempts to construct a class based on a class name in string form, and when a class file of the corresponding name is not found after traversing Classpah. Java.lang.CloneNotSupportedException does not support cloning exceptions. When the Cloneable interface is not implemented or the Clone method is not supported, the exception is thrown by calling its clone () method. The Java.lang.EnumConstantNotPresentException enumeration constant does not exist with an exception. This exception is thrown when an application attempts to access an enumeration object by name and enumeration type, but the enumeration object does not contain a constant. Java.lang.Exception Root exception. Used to describe what the application wants to capture. Java.lang.IllegalAccessException an illegal access exception. This exception is thrown when an application attempts to create an instance of a class by reflection, accesses the class property, calls the class method, and then cannot access the definition of a class, property, method, or constructor method. Java.lang.IllegalMonitorStateException violations of the monitoring State anomalies. This exception is thrown when a thread tries to wait for a monitor that does not own the object (O) or notifies other threads to wait for the object (O). Java.lang.IllegalStateException an illegal state of being abnormal. This exception is thrown when the Java environment and the application are not already in the legal invocation state of a method, and the method is called. Java.lang.IllegalThreadStateException an illegal thread state exception. An exception is thrown when the county seat is not in the legal calling state of a method and the method is called. Java.lang.IndexOutOfBoundsException index out-of-bounds exception. This exception is thrown when an index value that accesses a sequence is less than 0 or greater than or equal to the sequence size. Java.lang.InstantiationException instantiation of the exception. When trying to pass newThe Instance () method throws the exception when it creates an instance of a class that is an abstract class or interface. The java.lang.InterruptedException was aborted abnormally. This exception is thrown when a thread is in a long wait, hibernate, or other paused state while another thread terminates the thread through the interrupt method of the thread. Java.lang.NegativeArraySizeException array size is a negative value exception. This exception is thrown when an array is created with a negative size value. The Java.lang.NoSuchFieldException property has no exception. This exception is thrown when a property that does not exist for a class is accessed. The Java.lang.NoSuchMethodException method has no exception. This exception is thrown when a non-existent method of a class is accessed. Java.lang.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. Java.lang.NumberFormatException number format exception. This exception is thrown when an attempt is made to convert a string to the specified number type, and the string does not satisfy the format required by the number type. Java.lang.RuntimeException run-time exception. is the parent class of exceptions that can be thrown during normal operation of all Java virtual machines. Java.lang.SecurityException security Exception. Thrown by the security manager to indicate an exception that violates the security situation. Java.lang.StringIndexOutOfBoundsException string Index out-of-bounds exception. This exception is thrown when an index value is used to access a character in a string, and the index value is less than 0 or greater than or equal to the sequence size. There is no exception for the java.lang.TypeNotPresentException type. The exception is thrown when an app tries to access the type as a string representation of a type name, but the type is not found according to the given name. The difference between this exception and ClassNotFoundException is that the exception is unchecked (not checked) and ClassNotFoundException is a checked (checked) exception. Java.lang.UnsupportedOperationException method exceptions are not supported. An exception that indicates that the requested method is not supported. Exception Javax.sErvlet.jsp.JspException:Cannot Retrieve mapping   forAction/login (/login is your action name) possible cause action no longer struts-config.xml, or no matching action is found, such as using View Code

Non-check exceptions (unckecked exception): Error and RuntimeException and their subclasses. Javac does not prompt and discover such exceptions at compile time, and does not require the program to handle these exceptions. So if we want to, we can write the code to handle (using try...catch...finally) Such an exception, or we can not handle. For these exceptions, we should fix the code instead of going through the exception handler. Most of the reason for this exception is that there is a problem with code writing. If, except for 0 error arithmeticexception, the wrong coercion type casts error classcastexception, the array index crosses the arrayindexoutofboundsexception, Empty object nullpointerexception are used, and so on.

Check for exceptions (checked exception): Other exceptions except error and runtimeexception. Javac forces programmers to prepare for such exceptions (using try...catch...finally or throws). The method either captures it with the Try-catch statement and processes it, or throws it with a throws clause declaration, or the compilation does not pass. Such exceptions are generally caused by the operating environment of the program. Because the program may be running in a variety of unknown environments, and the programmer cannot interfere with how the user uses the program he wrote, the programmer should be prepared for such an unusual moment. such as SqlException, ioexception,classnotfoundexception and so on.

It needs to be clear that the inspection and non-inspection is for javac, so it is well understood and differentiated.

V. Throws function declaration

Throws declaration: If the code inside a method throws a check exception (checked exception), and the method itself is not completely disposed of, then javac guarantees that you must declare these possible exceptions using the throws keyword on the method's signature, or the compilation does not pass.

Throws is another way of handling exceptions, unlike Try...catch...finally,throws, which simply declares to the caller the exceptions that might occur in the function, but does not handle them in detail.

This exception can be handled because the method itself does not know how to handle such an exception, or to make the caller handle it better, and the caller needs to be responsible for the exceptions that may occur.

Vi. What is a check-type exception and what is a non-check exception

The simplest point of judgment is two:
1. A non-check exception that inherits from RuntimeException or error, and inherited from exception is a check-type exception (of course, runtimeexception itself is also a subclass of exception).
2. The non-check type exception can not be captured, and the check type exception must be handled with a try statement block or the exception to the superior method processing, in short, must write code to deal with it.

Java's exception structure is as follows. Which directly inherits the exception exception, must be caught, belongs to the Check type exception.

        // Run-time exception        Throw New RuntimeException ("No need to declare exceptions")        ; // Check for exceptions        Throw  New Exception ("Need to declare exception");

The exception is divided into two large exception types, running exceptions, and being checked for exceptions, the difference between the two kinds of exceptions:

1. Run-time exception

The characteristic of running an exception is that 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, it is not declared with the throws sentence, or it will be compiled.

2. Check exception

In addition to running exceptions, other exceptions belong to the checked exception, which is characterized either by try...catch capture processing or by throws statement declarations, or the compilation does not pass.

3, the difference between the two

A run exception indicates an exception that cannot be resumed by the program, and the cause of this exception is usually due to an incorrect operation. When an error occurs, it is recommended that the program be terminated

About exception Exceptions in Java

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.