Exception Handling Based on Java programming

Source: Internet
Author: User

Early programming languages (such as the C language) do not handle exceptions. Generally, a special value is returned or a flag is set in case of an error to determine whether an error has occurred. As the system grows, such error handling has become an obstacle for creating large maintenance programs. Therefore, exception handling mechanisms are introduced in some languages, for example, the exception handling statement "on error goto" in Basic, while Java creates a new exception handling mechanism based on C ++.

Java uses object-oriented methods to handle exceptions, classify various exceptions, and provides good interfaces. This mechanism provides a powerful way to control complex programs. At the same time, these exception codes are separated from the "regular" code, enhancing the readability of the program and making the program more flexible.

Another advantage of exception handling is that you can submit the problem without determining or handling the exception. On the other hand, the exception handling mechanism makes the error handling code more organized and easier to maintain. Next, let's take a look at how to handle exceptions in Java.

Java exception classes

In Java, each exception is an object, which is an instance of the Throwable class or other subclass. When a method encounters an exception, an exception object is thrown. The object contains the exception information. The method that calls this object can capture the exception and handle it.

The Throwable class has two standard subclasses: java. lang. Error and java. lang. Exception, that is, errors and exceptions. Error errors generally refer to problems related to virtual machines, such as system crashes, virtual machine errors, and dynamic link failures. Such errors cannot be recovered or cannot be captured, resulting in application interruption. Exception class refers to some exceptions that can be captured and may be recovered, such as array subscript out of bounds ArrayIndexOutOfBoundsExcepton, number division by zero, ArithmeticException, input/output Exception IOException, etc.

Tip: the Java compiler requires the Java program to capture or declare all non-runtime exceptions, such as FileNotFoundException and IOException. For such exceptions, unexpected results may occur if the program does not process them. However, exceptions may not be processed during running, because these exceptions are common and all processing may affect the readability and Running Efficiency of the program.

Java Exception Handling Format

Java exception handling is implemented through five keywords: try, catch, throw, throws, and finally. Generally, try is used to execute a program. If an exception occurs, the system throws an exception. In this case, you can catch it by its type, or finally (finally) is handled by the default processor.

Below is the basic form of Java exception handling program:

Try
// Program block during execution

Catch ExceptionType1e
// Processing of predictiontype1

Catch ExceptionType2e
// Process predictiontype2
Throw e
// Then throw this "exception"

Finally

Try block and catch statement

When a try statement is encountered, the framework of the "exception" is placed on the stack until all the statements in the try block are completed. If the try statement at the next level does not process an "exception", the stack will be opened until a try statement that handles this "exception" is encountered. The try program should contain a catch clause to specify the type of the "exception" you want to capture.

Tip: the first step to capture exceptions is to use try... Select the range where you want to capture exceptions. During execution, the code in the brackets will generate an exception object and be thrown. Then you can use catch Block to handle exceptions.

Throw and throws statements

Throw statements are used to explicitly throw an "exception ". First, you must obtain the instance handle generated by a Throwable class or other sub-classes, pass the parameters to the catch clause, or use the new statement to create an instance.

The following is the general form of the throw statement:

Throw ThrowableInstance


Tip: After the throw statement is executed, the running process stops immediately and the next statement of throw is also paused. Here, the new operator is used to create an instance of the Throwable class, which will be explained in detail in the next article on object-oriented programming.

The throws statement is used to indicate various "exceptions" that a member function may throw ". For most Exception subclasses, the Java compiler forces you to declare the "Exception" type thrown in a member function. If the "exception" type is Error or RuntimeException, or their subclass, this rule does not work. If you want to explicitly throw a RuntimeException, you must use the throws statement to declare its type.

Tip: Of course, you may not understand the above description, but it doesn't matter. Compile and run the following Java program (you have made a detailed comment for you) and you will understand a lot!

Now we use the following routine to illustrate the problem:

Class ThrowsDemo // class name. The corresponding java source file should be saved as: ThrowsDemo. java
Static void procedure throws Illegal
AccessException // throws statement
// Throw an IllegalAccessException exception.
System. out. println "inside procedure" // output text to indicate that proced is being executed.
An exception is thrown during the ure method.
Throw new IllegalAccessException "de
Mo "// generate a Throwable class instance and throw an exception

Public static void mainString args // start with the main method, and the program runs from here
Try // start of the try statement Block
Procedure // call the procedure method, which throws an exception

Catch IllegalAccessException e
// Handle exceptions of the IllegalAccessException type, catch statement Block
System. out. println "caught" + e


Program and execute the program. The process is as follows:

E/javacode/exception> java ThrowsDe
Mo
Inside procedure
Caught java. lang. IllegalAccessExceptio
N demo

Tip: As shown in the code above, we use a complete program to explain how to use try... Catch... Throw and other statements. Try... The exception is caught and then processed in the catch Block (here only the exception information is output ). Throws IllegalAccessException indicates that the program will throw an IllegalAccessException type exception. IllegalAccessException e generates an exception object, and then outputs the exception information using System. out. println.

Finally statement

Sometimes to ensure that a piece of code is executed no matter what exceptions occur, you can use the keyword finally to mark such a piece of code. A member function returns to the member function that calls it, or uses an uncaught exception or a clear return statement. The finally Clause always happens to be executed before the member function returns.

The following describes how to use the exception handling statements described above with a complete exception handling program:

Class ExceptionDemo // exception example, saved as ExceptionDemo. java
Static void procA

Try
System. out. println "inside procA ″
Throw new RuntimeException "demo ″
// Throw an exception
Finally
System. out. println "procA's finally" // Note: It will be executed no matter what happens !!
Static void procB
Try
System. out. println "inside procB ″
Return // return, which is actually returned after the finally statement is executed
Finally
System. out. println "procB's finally ″
Public static void mainString args
Try
ProcA
CatchException e
System. out. println "catch" + e
Procb

Tip: In the complete program above, the finally code in braces will be executed under any circumstances. In procB, the return statement does not return immediately, so pay special attention to this. You can try to execute the above Program (Compilation and execution are similar to the previous example )?

So far, Java's process control has been completely completed. To really understand and master them, you only need to go through a lot of exercises. The good way is to modify each of the above programs to implement the functions you want, and basically Understand Java's process control. To write a Java program, it is critical to be familiar with Java Process Control and exception handling. In these two phases, we use a large number of routines to illustrate how the Java language uses Flow Control statements, and briefly introduce the exception handling statements that are frequently used in flow control.

 

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.