Java exception Summary

Source: Internet
Author: User

This is the same as the java summary interface and abstract class. Skip the basic syntax without chatting, just say something tricky and some good practice.


Syntax:

Exception is inherited from Throwable. Throwable and another son is Error, but it is generally not used. However, some two hundred and five interviewers prefer to write several types of questions, so they still need to know that there is an Error. Exception can be divided into checked and unchecked.


Java checked exception has always been a controversial issue. Bruce, author of Thinking in Java, designer of C # And Martin Fowler both question the checked exception. A typical objection is: "We felt it was unrealistic to require the programmer to provide handlers in situations where no meaningful action can be taken." This is too affordable. How can magically know that all callers that call this method can handle specific exceptions when writing a method to caller?


The basic syntax for Exception is that if the override method of the subclass throws an exception, it can only throw the exception declared by the parent method or the subclass of the exception. It should be noted that the word "back" is also written in a way that does not have this restriction for constructor. Subclass can throw any exception. The exception declared by the parent constructor. The sub-class constructor cannot capture the exception declared by the parent class. this is easy to understand. If the parent class structure is wrong, the son can handle it and give birth to himself. Where can I find my son without him? Of course, you can tell me about Lao Tzu's green hat.


Practice:

1. Try not to perform complex operations in the constructor, and try not to let constructor throw an exception. If an exception is thrown in the constructor, use the nested try block as follows:

1: public class Cleanup {
2: public static void main (String [] args ){
3: try {
4: InputFile in = new InputFile ("Cleanup. java ");
5: try {
6: String s;
7: int I = 1;
8: while (s = in. getLine ())! = Null)
9:; // Perform line-by-line processing here...
10:} catch (Exception e ){
11: System. out. println ("Caught Exception in main ");
12: e. printStackTrace (System. out );
13:} finally {
14: in. dispose ();
15 :}
16:} catch (Exception e ){
17: System. out. println ("InputFile construction failed ");
18 :}
19 :}
20 :}

Instead of using finally for cleanup.


2. One of the basic usage principles of exception is that exception is not designed to control program flow. This is very simple. Let's refer to an example of objective java.

1: // Horrible abuse of exceptions. Dont ever do this!
2: try {
3: int I = 0;
4: while (true)
5: range [I ++]. climb ();
6:} catch (ArrayIndexOutOfBoundsException e ){
7 :}

What I really want to explain is that the principles mentioned above are right, but it is wrong to go to extremes. Some people write a lot of if... The else statement tries to consider various situations. Some colleagues recently told a joke and I think it can help to explain this problem.

==================================

One day, when the teacher tried to test the students' IQ in class, he asked a boy, "there are ten birds in the tree, and how many birds are left when one is shot and killed ?"

The boy asked, "Is it a pistol without sound, or is it a gun without sound ?"

"No ."

"How big is gunshots ?"

"80 ~ 100 decibels ."

"That means it will shake your ears ?"

"Yes ."

"Isn't it illegal to beat birds in this city ?"

"No offense ."

"Are you sure the bird is really killed ?"

"OK." The teacher is impatient. "Please, just tell me how many are left. OK ?"

"OK. Are there any deaf birds in the bird ?"

"No ."

"Is there a problem with the intelligence of a bird? I am so stupid that I don't know how to fly when I hear a gun ?"

"No, I have an IQ of more than 200 !"

"Are they in cages ?"

"No ."

...

====================================

There are a bunch of "exceptions" in the future. We cannot write programs in real time.

If (birds are deaf)

...

Else if (birds are dummies)

...

Else if (the bird is lame)

...

The principle should be: if some situations are "exceptions", use exception. Do not write a bunch of defensive judgments very diligently. We don't have any small boys in the story. Do not return the Java program to the C language. Another example is FileNotFoundException. java I/O does not allow you to call exists () to check the file every time you use it. I think it is not just because the file in that millisecond exists, when the next step is run, the file in the next millisecond disappears. Sun doesn't think your character is so bad. The idea is that if you think the file exists, you can use it directly. If it does not exist, you can handle it as an exception. Don't let a bunch of if... The else program is corrupted.


3. exception A typical usage is to verify the validity of parameters in the method body.


1: public BigInteger mod (BigInteger m ){
2: if (m. signum () <= 0)
3: throw new ArithmeticException ("Modulus <= 0:" + m );
4:... // Do the computation
5 :}

Many also use assert statements, such as Assert. notNull (object ). Manually throwing an exception can throw a specific type, making the assert statement more convenient. It can be selected based on the actual situation.


4. As mentioned above, the checked exception itself is not properly designed in java. I tend to say that we should promptly translate the checked exception into unchecked. I know one of the exception handling principles is that if you don't know how to handle it, don't catch it. For checked exception, it is too annoying to use force. If the caller does not know how to handle it, keep it for the upper-Layer Program... The underlying program will not be processed. Generally, the upper-layer program will not know how to handle it. It is better to handle it as much as possible in the underlying call (this case is rare, logs cannot be processed. Or, it is converted to a RuntimeException and the burden caused by the checked exception is eliminated. note: In the process of translating an exception, do not throw the original exception, but place it in the argument of the exception constructor, new RuntimeException (e ). This is a basic thing, not to mention.


5. Don't swallow exception. This is too basic, not to mention.


6. When an exception is encountered, it should be recorded in the log, rather than simply a print stack. The log4j api can accept Throwable as a parameter.


7. the exception thrown at each layer must be meaningful to the current layer. For example, if the persistence layer has a problem, on the UI, you tell the client that the hibernate session is closed and you cannot continue to load data, the customer thinks that your program will hibernate like a bear. Even below the UI Layer, the underlying exception, such as SQL exception, should not be crawled into the domain layer for processing


8. The lang Package of apache commons contains the ExceptionUtils class. If you are playing exception, you 'd better put this tool in your pocket.

9. exception is part of the design, but it is different from the API design. We usually do not design a destroyBaghdad () function when designing an API. We usually write destroyCity (Baghdad ). This is intended for reuse. In other words, when you design an API, you always pretend to forget to use case (caller) and write the API that is suitable for reuse. Although the above example use case is destroy Baghdad, you still need to write a more general destroyCity function, and then pass the city name as a parameter. however, the exception design should not be done in the same way, because it is hard for you to think about reuse, and whether the exception you declare can always be properly handled under any circumstances. For example, this is my temporary example. The image is too advanced, but the technology is too advanced. When we write A print () program to printer A, print (), there is no paper to throw A checked NoPaperException, at this time, Tino's processing program can automatically load paper (currently such advanced features are being developed by Bell Labs ). Maybe there is a new type of printer B that always adds paper first and then prints, so there will never be NoPaperException. If the printer is an old-fashioned printer C, it does not automatically load the paper, and NoPaterException is not enough to handle. The philosophy of checked exception is to force caller to process it. As shown in the preceding example, only printer A needs to be able to handle NoPaperException. Printer B does not need to handle exception. Printer C cannot handle exception. therefore, | "yes" processing is too strict. In general, checked exception should not be used. we can let the print statement throw an unchecked exception. A reminder that the caller can process it, but the caller that should not process it is not forced to process it.

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.