"Java Advanced Chapter" "Lesson two" exception handling

Source: Internet
Author: User
Tags finally block throwable

Concept

The existence of exception handling is to:

Allows programmers to skip issues that cannot be handled, to continue to develop subsequent work, or to make smarter handling of exceptions.

There is a class of objects in Java called "Exception objects."

When the exception occurs, it will be a dark war pre-set, throw (throw) represents the current state of the object; throwing is actually a special way of returning, the thread pauses and exits the call layer by level until an exception handler is encountered (Exception Handler) .

The exception handler can catch (catch) the exception object and then, depending on the object, determines whether the next step is to alert the user, process or exit the program, and so on.

Basic structure

The exception handler consists of a try, catch, finally (this can not) and subsequent blocks:

Try  {  ...;} Catch () {  ...;} Catch () {  ...;} finally  {  ...;}

The exception handler monitors the block behind the try, which requires a parameter in the parentheses of the catch to represent the type of exception that is requested for catching. The catch captures the appropriate type and its derived class .

A try-monitored library may throw more than one type of exception, so an exception handler can have multiple catch modules.

Finally, the program block, whether or not an exception occurs , is executed.

In try, we put in a program that could be faulted, need to be monitored , and design an exception-handling scenario in the catch.

Simple example

1  Public class Both2 {3      PublicBoth ()throwsIOException4     {5BufferedReader br =NewBufferedReader (NewFileReader ("file.txt"));6         Try 7         {8StringBuilder SB =NewStringBuilder ();9String line =br.readline ();Ten  One              while(Line! =NULL)  A             { - Sb.append (line); -Sb.append ("\ n"); theline =br.readline (); -             } -String everything =sb.tostring (); -         }  +         Catch(IOException e) -         { + e.printstacktrace (); ASystem.out.println ("IO problem"); at         } -         finally  -         { - br.close (); -         } -     } in}

Line 19th, if we catch such an exception (that is, the IOException class object's E), you can object to that object. For example, call the object's Printstacktrace () to print out the status of the current stack.

Regardless of whether there is an exception, the program eventually enters the finally block, emptying the resource that the file descriptor occupies.

Exception class Trowable

Exception classes in Java are inherited from the Trowable class. An object of the Throwable class can be thrown (throw).

Throwable objects can be divided into two groups.

One group is the unchecked exception (orange in the figure), and the exception handling mechanism is often not used for this set of exceptions:

the error class usually refers to an internal error in Java and an error such as resource exhaustion. When error (and its derivative classes) occur, we cannot resolve the error at the programming level, so we should exit the program directly.

runtimeexception (and its derived classes) are caused by the Java program itself, that is, because programmers make mistakes in programming.

RuntimeException can be avoided entirely by correcting Java programs. For example, to convert an object of one type to another type that does not have an inheritance relationship, that is, classcastexception. Such exceptions should and can be avoided.

One group is the checked exception:

These classes are programmed to interact with the environment causing the program to fail at run time.

For example, when reading a file, because the file itself is wrong, ioexception occurs. Another example is the Web server temporarily changes the URL point, causing malformedurlexception. File systems and Web servers are outside of the Java environment and are not controlled by programmers. If the programmer can anticipate exceptions, the exception handling mechanism can be used to prepare the response plan. For example, if the file is faulty, remind the system administrator. For example, when a problem occurs on the network server, remind the user and wait for the network server to recover.

The exception handling mechanism is primarily used to handle such exceptions.

Exception Handling Examples

1  Public class Both2 {3      Public Static voidMain (string[] args)4     {5Battery Abattery =NewBattery (2); 6Abattery.usebattery (-2.5);7     }8 }9 Ten classBattery One { A     Private DoublePower = 0.0;//Percentage of battery -Battery (Doublep) -     { thePower =p; -     } -  -      Public BooleanUsebattery (Doublep) +     { -         Try  +         { A test (p); at         }  -         Catch(Exception e) -         { -System.out.println ("Catch Exception"); - System.out.println (E.getmessage ()); -p = 0.0; in         } -  to         if( This. Power >=p) +         { -              This. Power = This. Power-p; the             return true; *         }  $         ElsePanax Notoginseng         { -              This. Power = 0.0; the             return false; +         } A     } the  +     Private voidTestDoublePthrowsException -     { $         if(P < 0) { $Exception e =NewException ("P must be positive"); -             Throwe; -         } the     } -}

The result of the operation is:

Catch Exception
P must be positive

Custom exceptions

Cond..............

......................................

....................................

Daughter-in-law to bring rice.

"Java Advanced Chapter" "Lesson two" exception handling

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.