Java Learning lesson 19th (exception Handling in Java programs (ii))

Source: Internet
Author: User
Tags finally block

Catch form of exception handling:

This is how the exception can be dealt with in a targeted manner


Six, try, catch understanding


Specific format:

try{//need to be detected exception code}catch (Exception class variable)//change the amount used to accept the object that the exception occurred {//the code that handles the exception}finally{//code that is bound to be executed}

These three blocks of code are a whole.

Try is an attempt, catch capture, finally final

When to use Try&catch, when to throw?

When defining the function, if you can handle the problem, then use Try&&catch, and then use the throw

Code Demo:

Import Java.util.*;class Fuexception extends Exception{fuexception () {}fuexception (String s) {super (s);//exception have// System.out.println (s);}} Class Exceptiondemo {//either capture, or throw public int method (int[] Arr,int index) throws Fuexception{if (index<0) {throw new Fuexception ("The index is Fushu");    return arr[index];}} public class Main{public static void Main (string[] args)//throws fuexception{int[] A = new int[10]; Exceptiondemo C = new Exceptiondemo (); try {int num = C.method (a,-2); System.out.print ("num" +num); catch (Fuexception e) {System.out.println ("angle marked negative!"); The/E object can not be used, here are some common methods System.out.println ("Message:" +e.getmessage ()); System.out.println ("String:" +e.tostring ());//tostring can omit//print exception information e.printstacktrace ();// The default exception handling mechanism for the JVM is to invoke this method of the exception object}}}

/* Real log file creation

*log four (Java;;)

*{

*

*}

*/Its shorthand form: log4j


Seven, multiple catch cases

If more than one exception is thrown while the program is processing

Import Java.util.*;class Fuexception extends Exception{fuexception () {}fuexception (String s) {super (s);//exception have// System.out.println (s);}} Class Exceptiondemo {public int method (int[] Arr,int index) throws Fuexception,nullpointerexception{if (index<0) { throw new Fuexception ("The index is Fushu");    if (arr==null) {throw new NullPointerException ("No array entity");//customizable}return arr[index];}} public class Main{public static void Main (string[] args)//throws fuexception{int[] A = new int[10]; Exceptiondemo C = new Exceptiondemo (); try {int num = C.method (a,2); System.out.print ("num" +num); catch (Fuexception e) {System.out.println ("angle marked negative!");} catch (NullPointerException e) {//e.printstacktrace (); System.out.println ("Message:" +e.getmessage ());} Multiple catch cases, if there is the following catch situation, can not be the top of the house, will accept all objects catch (Exception e) {///parent of the catch room at the bottom, otherwise the compilation fails//If there is a situation outside of the catch, virtual Opportunity processing}}}



Eight, the principle of handling anomalies


When does the try really work?

The most fundamental core: as long as the use of the method of declaring the exception, you have to try, as long as the code in the exception to throw the action, if you can handle it with a try, see the exception to deal with, no exception does not need to deal with. Note : No errors, not to write try, not only meaningless, there are drawbacks, if you really want to deal with the exception, but do not know what is abnormal, then can only write exception, once the unknown exception really happened, but there is a pre-processing way to deal with what do not know, This exception is disposed of, once disposed of, it is equivalent to the exception is hidden, but the program is still in normal execution. So, as long as there is no problem, do not deal with, as long as the problem occurred, see, and then consider whether to deal with the problem

The principle of exception handling:

1. Inside the function if you throw an exception that needs to be detected, the function must be declared, otherwise it must be caught inside the function with Try&&catch, otherwise the compilation fails

2. If you call a function that declares an exception, either Try&&catch or throws, or the compilation fails

3. When to catch, when throws?

Functions can be resolved internally, with catch

Can not solve, with throws, by the caller to solve

4. A function if more than one exception is thrown, then the call must correspond to more than one catch, for targeted processing

(inside there are several exceptions that need to be detected, you will throw a few exceptions, throw a few, catch a few)


IX. finally block of code


Application of/*finally:
* Use to the most finally place, such as the database
* For example: Open Baidu, search
* Connect to Database
* Query: If the exception, the query process problems
* Close Connection
* If an exception occurs and the connection is not closed, the database resource is also wasted, so the connection must be executed regardless of whether an exception occurs
* Then release the resource, so close the connection definition in finally
*/

Therefore: all resources need to be closed, must be defined in the finally.


How to try,catch,finally block combinations of code:

1,try,catch,finally (three are common)

2, try, catch, no need to release the necessary resources, there is no need to define the finally

3, try, finally exception can not be directly catch processing, but resources must be closed

void Show ()//throws Exception, without declaration, because the catch has already been processed {try {throw new Exception ();  } Have catchcatch{...  }

void Show () throws exception//no catch, declare {try {throw new Exception ();  } No catchfinally  //Connection resources, there is an exception, but this exception is not necessarily to deal with, but the resources must be closed, because in the internal open, others do not know {  ...   }}




Java Learning lesson 19th (exception Handling in Java programs (ii))

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.