Java Fundamentals--exception--parsing

Source: Internet
Author: User
Tags switch case throwable try catch

Brief introduction

Exception handling is one of the most important features of the Java language, as explained in the article "Three rules for effective Exception handling": It mainly helps us to solve the following three problems in the debug process.

    • What's wrong?
    • Where's the error?
    • Why error

The Java language can be said to provide an overly sophisticated exception handling mechanism, so that later "thinking in Java" author Bruce Eckel has specifically addressed him. The exception mechanisms in Java include the Error and Exception two sections. They all inherit from a common base class Throwable. Errors are some of the bugs that occur in the JVM's operation, although they are not part of the developer's domain, but some of the error is caused by code, such as Stackoverflowerror, which is often caused by recursive operations, which tell developers that you are generally not able to save, only by the JVM. And exception assumes that the programmer will handle these exceptions, such as a database connection exception, then we can handle the exception, reconnect, and so on. The exception is divided into two types, the check type (checked) and the unchecked type (unchecked). Checking the type of exception means that the programmer explicitly declares or uses a try. Catch statements to handle exceptions, rather than checking for type exceptions, do not have these limitations, such as our common nullpointerexception is non-check type and he inherits from RuntimeException. Java is the only one in the mainstream programming language that advocates the use of check-type exceptions, at least for sun. The controversy over the use of checked or unchecked anomalies has been intense. The following is a class diagram for exceptions in the Java language.

Basic Use

We have been exposed to some exceptions when using some Java files or database operations, such as IOException, SqlException, and so on, which are declared to be likely to throw some kind of exception, so we need to capture it. This requires a basic try: Catch statement. is a basic structure that we often write. A try statement block writes code that may throw an exception and then captures it in a catch statement block. We see that the catch parameter is written in a exception object, which means that this block of statements captures all the exceptions of the check type (although this is not a good way to write, and later on), finally will always be in the final execution, usually we in the inside to deal with some cleanup work, such as closed file stream or database, network and other operations.

Of course, the above statement block structure is flexible, but try is necessary, catch and finally have at least one, of course, the number of Catche can have multiple. Sometimes many types of exceptions may be thrown in a try statement block, and at this point we can write multiple catch statements to catch different types of exceptions, which is a good wording:

        try{            //... Invoke some methods that may throw exceptions        }catch (ExceptionType1 e) {            //...handle exception        }catch ( ExceptionType2 e) {            //...handle exception        }catch (Exception e) {            //...handle exception        }finally{            //.. Do some cleaning:close the file db etc.        }

When the exception does not satisfy the first two type, exception will catch the exception. We found this to be similar to the structure control statement for switch case, but in fact, once a catch has been matched, the others will not match, a bit like a case with a break. It is important to note that catch (Exception) must be written on the last side, the catch is ordered to match, and later matches the Exception subclass, the compiler will error.

First Learning Try: Catch is always attracted to it, so a lot of this result is used to achieve some "robustness". (This statement is also the programmer's favorite). But when the try statement actually executes, it causes the stack operation. That is, to save the entire method's call path, which is bound to make the program slow. Fillinstacktrace () is a method of throwable that is used to perform stack operations, which are thread-synchronized and time-consuming. There was a very classical discussion of the problem here in StackOverflow, the original text. It is true that when we do nothing in a try, or just perform a simple call like addition, the execution efficiency is almost the same as a control statement such as Goto. But who would write such a code?

In short, do not always attempt to control the structure of the program through try catch, no matter from the efficiency or the readability of the code is not good.

Try catch the good side

Try catch is not recommended for the control of the program structure, but it is also of great significance, one of the benefits of its design is that a developer can handle a thing as a transaction, and that the transaction is also an important concept in the database, for example, the transaction that completes the order, This includes a sequence of actions, including user-submitted orders, merchandise out-of-stock, correlation, etc. When one of the actions in this sequence fails, the data is restored to a normal point, so that it does not appear, you pay the bill, the goods do not give you the situation. In the TRY statement block, as in the case of executing a transaction, when an exception occurs, it is handled uniformly in the catch, guaranteeing the complete lossless of the data. In fact, a lot of bad code is also because there is no good use of the Catch statement language, resulting in a lot of exceptions are drowned, this is introduced later.

customizing the detailed exception

We can define our own exceptions to capture the processing of a specific example. Create your own exception class, and you can inherit exception or runtimeexception directly. The difference is that the former is the abbreviation type, and the latter is the check type exception. Sun's official power is quite traditional, and he advises developers to check the type of exception that you must deal with. The following is a simple exception class for the definition.

public class Simpleexception extends exception{    simpleexception () {}    simpleexception (String info) {        Super (info);}    }

We have covered two construction methods, which is meaningful. By passing string arguments, we can record detailed information when we create an exception object, so that when the exception is captured, the details we defined earlier are displayed. For example, use the following code to test the exception class we define:

public class Test {public    void fun () throws simpleexception{        throw new Simpleexception ("Throwing from Fun"); 
   
    } public    static void Main (string[] args) {        Test t = new Test ();        try{            T.fun ();        } catch (Simpleexception e) {            e.printstacktrace ();}}    }
   

Running will get the following result Printstacktrace is the method of printing the call stack, he has three overloaded methods, the default is to output information to System.err. So we can clearly see the process of the method call, a bit like the interruption in the operating system, to protect the scene.

Simpleexception:throwing from Fun
At Test.fun (test.java:4)
At Test.main (test.java:9)

a slightly troublesome grammar

Exceptions that we implement ourselves sometimes use to inherit these features, and there are some limitations when it comes to exception inheritance. That is, the subclass cannot throw a base class or an exception that is not thrown in the implemented interface. For example, there are the following interfaces:

Public interface Interfacea {public    void F () throws IOException;}

Our test class implements this interface, then test's F method either does not throw an exception, or can only throw ioexception, in fact, there are more trivial rules, detailed can refer to "Java puzzlers" 37th puzzle. So this is just the opposite of traditional inheritance and implementation interfaces, and object-oriented inheritance is magnified, and this is just shrinking.

the controversy about checked and unchecked

In the traditional view, Sun argues that "because the Java language does not require methods to capture or specify runtime exceptions, it RuntimeException is appealing to programmers to write code that throws only run-time exceptions or make all their exception subclasses inherit from them." These programming shortcuts allow programmers to write Java code without being disturbed by all the critical errors from the compiler, and without having to specify or catch any exceptions. While this may seem convenient for programmers, it avoids Java captures or specifies the intent of the requirements, and can cause problems for programmers who use the classes you provide. He emphasized to try not to use unchecked anomalies.

But Eckel, author of Thinking in Java, has changed his mind, and an article on his blog (the article is very good and simple to express) specifically lists the drawbacks of using checked anomalies. He points out that the formal check type makes a lot of exceptions impossible for programmers to discover. Developers have greater freedom to decide whether to handle an exception. Even if you forget to deal with an exception, he will throw it somewhere and be found without losing it. The checked exception makes the code less readable and is secretly encouraging people to drown out anomalies. Now many Ides are reminding us that a method is going to run out of the ordinary, and then even automatically generate catch or throw for us. This is a very scary behavior, which leads to many of our catch statements that have nothing in it, just like a trap.

Another problem with the checked exception is that the code is difficult to maintain, because to add throws to the method declaration, if the implementation of the method changes and a new exception occurs, then we have to modify the declaration of the method. It is also a bit bad to not be able to clearly reveal the characteristics of the anomaly. For example, when we log in to the score system, if the user name is registered, we may expect a nosuchstudentexception but the actual view may be a sqlexception. The 43rd article in effective Java : Throws an exception that fits the abstract. This is the principle that the thrown exception should be consistent with the abstract concept, for example, we are in a system no matter what the specific problem, but most of what we see is just sqlexception.

With regard to how to choose, Bloch's recommendation is to use a check-type exception for recoverable conditions and a run-time exception for programming errors. my feeling is to choose to check the exception must be "processing", of course, the processing here must be real processing rather than empty write a catch statement just. I don't know how Java will treat checked and unchecked in the future, after all, Java is the only mainstream programming language that supports checking exceptions.

good rule.

Fail Fast: It is to throw an exception as early as possible, so that there are locations and reasons for more accurate positioning errors. This is also better understood, such as the user name is not valid when thrown immediately, usernameillegalexception, if not timely throw an exception, then the illegal name may lead to a sqlexception, But the program to give you a sqlexception, you are very difficult to directly know that must be the user name is not legal caused. The idea of Fail fast is also well embodied in the ArrayList mechanism of Java implementation.

Catch late: Don't handle exceptions prematurely in a method, especially if you don't do anything, it's even scarier. Because if the "none" processing is likely to cause a new exception to continue later (such as the wrong user name will raise some of the subsequent column errors, the program can not handle the wrong user name, the latter will not be processed), which adds a lot of difficulty in debugging. A good experience is to pass exception handling to the caller, which throws the exception in a timely manner, and the technique is implemented in a way that declares the throws of the method, marking out all the exceptions that might be thrown.

Java Fundamentals--exception--parsing

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.