Java Basics-Exception handling

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

When the program is running, a run-time error occurs if the JVM detects an operation that cannot be performed.

In Java, run-time errors are thrown as exceptions. An exception is an object that represents an error or condition that prevents the program from executing properly. If the exception is not handled, then the program terminates abnormally.

An exception is thrown from a method. The caller of the method can catch and handle the exception.

Execution of the throw statement is called throwing an exception. An exception is an object created from an exception class.

When an exception is thrown, the normal execution process is interrupted. As its name suggests, "Throwing an exception" is a way of passing an exception from one place to another. The statement that invokes the method is contained in a try block and a catch block.

The throw statement is similar to a method call, but unlike the calling method, it calls a catch block. In a sense, a catch block is like a method definition with parameters that match the type of the value thrown. However, unlike a method, when the catch block is executed, program control no longer returns to the throw statement, but the next statement after the catch block is executed.

An exception may be thrown directly by a throw statement in a try block, or by invoking a method that might throw an exception.

Advantages of using exception handling: It can cause a method to throw an exception to its caller, and the caller handles the exception. Without this capability, the called method must handle the exception itself or terminate the program. The method being called usually does not know what to do in case of an error, which is the general case of the library method. The library method can detect errors, but only the caller knows what needs to be done when an error occurs. The most fundamental advantage of exception handling is that the detection error (done by the called method) is separated from the processing error (which is done by the calling method).

Exceptions are objects, and objects are defined using classes. The root class of the exception is java.lang.Throwable.

There are many predefined exception classes in the Java API.

        

The Throwable class is the root class for all exception classes. All Java exception classes are inherited directly or indirectly from Throwable. You can create your own exception classes by inheriting exception or exception subclasses.

These exception classes can be divided into three main types: System errors, exceptions, and run-time exceptions.

System errors are thrown by the Java Virtual machine and are represented by the error class. The error class describes an internal system error. Such errors seldom occur. If so, there is almost nothing to do except to inform the user and to terminate the program as safely as possible.

Exceptions are represented by the exception class, which describes errors caused by programs and external environments that can be captured and processed by the program. ClassNotFoundException, IOException

A run-time exception is represented by the RuntimeException class, which describes a programming error, such as a wrong type conversion, access to an out-of-bounds array, or a numeric error. Run-time exceptions are typically thrown by a Java virtual machine. ArithmeticException, NullPointerException, indexoutofboundsexception

RuntimeException, error, and their subclasses are called exempt exceptions. All other exceptions are called required exceptions, meaning that the compiler forces programmers to check and process them through try-catch blocks, or declare them in the method header.

In most cases, the exception of exemption will reflect the non-recoverable logic error in the program design. For example, if an object is accessed by a reference variable without assigning a value to it, the nullpointerexception is thrown, and if an array's out-of-bounds element is accessed, an Indexoutofboundsexception exception is thrown. These are logic errors that must be corrected in the program. Exemption exceptions may occur anywhere in the program. To avoid excessive use of try-catch blocks, the Java language does not enforce the requirement to write code to capture or declare exemption exceptions.

The exception handler is found by starting with the current method, along the method call chain, in the direction of the reverse propagation of the exception.

Java's exception handling model is based on three operations: declaring an exception, throwing an exception, and catching an exception.

  declaring exceptions

In Java, the currently executing statement must belong to a method. The Java interpreter calls the main method to start executing a program. Each method must declare the type of required exception that it may throw. This is called declaring an exception. Because system errors and run-time errors can occur in any code, Java does not require that the declaration error and RuntimeException (exemption exceptions) be displayed in the method. However, other exceptions that the method throws must show the declaration in the method header, so that the caller of the method is told that there is an exception.

If the method does not declare an exception in the parent class, it cannot be inherited in the subclass to declare the exception.

  Throw exception

  The program that detects the error can create an instance of the appropriate exception type and throw it, which is called throwing an exception.

IllegalArgumentException ex = new IllegalArgumentException ("wrong Argument");

Throw ex;

Or, depending on your preference, you can also use the following statement:

throw new IllegalArgumentException ("wrong Argument");

The keyword that declares the exception is throws, and the keyword that throws the exception is throw.

  Catching exceptions

  If no exception occurs during the execution of the try block, the catch clause is skipped.

 If a statement in a try block throws an exception, Java skips the remaining statements in the try block, and then begins the process of finding the code that handles the exception. The code that handles this exception is called the exception handler, and it can be found in the reverse propagation direction of the exception, starting with the current method and following the method call chain. Check the catch block individually from the first to the last, and determine if the exception class instance in the catch block is the type of the exception object. If it is, assign the exception object to the declared variable, and then execute the code in the Catch block. If the exception handler is not found, Java exits the method, passing the exception to the method that called the method, and continues the same process to find the processor. If the processor is not found in the called Method chain, the program terminates and prints an error message on the console. The process of finding a processor is called catching an exception. P393

  You can derive a variety of exception classes from a common parent class. If a catch block captures the exception object of a parent class, it captures the exception object for all subclasses of that parent class.

The order in which exceptions are specified in the catch block is very important. If the catch block of the parent class appears before the catch of the subclass, it causes a compilation error.

Java forces the programmer to handle the required exception, and if the method declares a required exception (that is, an exception other than error or runtimeexception), it must be called in Try-catch or declared to throw an exception in the calling method.

  Getting information from an exception

  The exception object contains valuable information about the exception. You can use the instance methods in the following java.lang.Throwable classes to get information about the exception. The Printstacktrace () method prints the stack trace information on the console. The Getstacktrace () method provides programmatic way to access the stack trace information that is printed out by Printstacktrace ().

In an exception event, execution will still continue. If the processor does not catch the exception, the program will suddenly break.

finally clause

The finally clause is always executed regardless of whether the exception is generated.

Sometimes, you want to execute some code, whether or not the exception appears or is caught. Java has a finally clause that can be used to achieve this.

In any case, the code in the finally block executes, regardless of whether an exception occurs in the try block or if it is caught. Consider the following three possible scenarios:

(1) If no exception occurs in the try block, execute finalstatements, and then execute the next statement of the try statement.

(2) If a statement in the try block causes an exception and is caught by a catch, then skips the other statements of the try block, executing the catch block and the finally clause. Executes the next statement after the try statement.

(3) If a statement in the try block causes an exception, but is not caught by any catch block, the other statements in the try block are skipped, the finally clause is executed, and the exception is passed to the caller of the method.

The finally block executes even if there is a return statement before the finally block is reached.

When to use exceptions

The method should throw an exception when the error needs to be handled by the caller of the method.

  The try block contains code that is normally executed. The catch block contains code that executes under exceptional circumstances. Exception handling separates the code that handles the error from the normal program design task, which makes the program more readable and easier to modify. However, it should be noted that because exception handling requires the initialization of a new exception object, it needs to be returned from the call stack, and the exception needs to be propagated along the method call chain (note that the direction of the method call and the direction of the exception propagation are reversed) in order to find its exception handler, so exception handling usually requires more time and resources.

The exception appears in the method. If you want the caller of the method to handle the exception, you should create an exception object and throw it. You do not need to throw an exception if you can handle the exception in the method where the exception occurred.

To re-throw an exception

If the exception handler cannot handle an exception, or if it simply wants its callers to notice the exception, Java allows the exception's processor to re-throw the exception.

Try {    statements;} Catch (Theexception ex) {    perform operation before exits;     Throw ex;  }

The statement throw ex re-throws an exception to the caller so that the caller's other processor gets the chance to handle the exception ex.

Create a custom exception

You can define a custom exception class by deriving the Java.lang.Exception class

If you encounter a problem that cannot be properly described with a predefined exception, you can create your own exception class by deriving the exception class or its subclasses, such as IOException.

Java Basics-Exception handling

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.