Java Basic Learning Summary-Exception handling

Source: Internet
Author: User

First, the concept of abnormal

  An exception is a run-time error that occurs when a program starts executing after the execution period . It is most important to observe the wrong name and line number when an error occurs.

  

1 Packagecn.javastudy.summary;2 3 Public classtestex{4 5 Public Static voidMain (String args[]) {6intarr[]={1,2,3}; 7 System.out.println (arr[2]); 8/**9 * Here Try......catch is used to capture the exception generated by the 0, the basic format is: Ten * try{11 statements;//may produce an exception to the statement 12 ......                 }14 catch (Throwable-subclass e) {//exception parameter E15 statements;//exception handler 16 ...... }18*/19Try{System.out.println (arr[2]/0);21}Catch(ArithmeticException AE) {//here is the type declaration of this exception parameter, which is declaring what type of exception this exception belongs toSYSTEM.OUT.PRINTLN ("The system is being maintained, please later!") ");23/**24 * This error stack information is printed using the Printstacktrace () method. 25 * The so-called "error stack Information" refers to the error that may be caused by the previous error, 26 * and the previous error may be caused by another error. What caused the error, 27 * All the error messages are printed out to know. This information often gives us programmers the ability to debug wrong hints. 28 * This information is useful, so we often use this method to print out the error message. 29 * Default printing error message The use of this method is also printed out*/31ae.printstacktrace ();32         }33     }34}

Code Run Result:

  

Summary:

Exceptions are errors that occur during run time, and the way in which Java handles such errors after a run occurs is to first find the appropriate catch code to see if the catch is used to catch the exception, and if a catch exists, then Java automatically jumps to the catch to handle the exception. If there is no catch, then Java will throw the error and print out the relevant error message. If you want to catch an exception by catching it, you have to write a try, and no try can be used to write a statement that is likely to produce an exception, and the catch is written with the exception that occurs when the statement in the try is run catch,try.

The method declaration can indicate the type of exception that this method is likely to throw, throw an exception with throw, and declare that a possible exception with throws declaration after the method must be captured.

  

Ii. Classification of anomalies

  

Third, abnormal capture and processing

Five keywords for Java exception handling:try, catch, finally, throw, throws

  

  

  

  

It is a good programming habit to have to deal with an exception after it has been caught, even if the error message is printed out. If not, it is to hide the error quietly, but this error is still there, but can not see it. This is a very dangerous programming habit, absolutely can not do this, catch the exception must be processed, really can not handle the exception thrown out, let other methods to deal with. In short, it is not possible to catch an exception and do not do the corresponding processing, this is a very bad programming habits.

There is a simple way of saying "throws Exception" because the Exception class is the base class for all the exception classes that can be handled. So throwing the exception class throws all the exception classes that can be handled. After using "throws Exception" to throw all the exceptions that can be handled, these thrown exceptions are given to the Java Runtime System for processing, and the process is to print out all the associated error stack information for these exceptions. In addition to testing, in the actual programming, in the main method of throwing exception is a very bad programming habit, you should use Try......catch to catch the exception and deal with the catch-up exception. Not directly in the main method to throw the exception to the Java Runtime system output is finished, this is an irresponsible performance. If you want to write programs that are particularly robust, it is essential to use Try......catch to catch exceptions and to handle the catch-up exceptions.

Iv. Try...cath ... Finally statement 4.1. Try Statement

  

4.2. Catch statements

  

We generally use printstacktrace () This method to print the information of the exception, using this method to print out all the error information, including the use of the GetMessage () method to print out the information. Use this method before you can invoke it by using a new Error object. Because it is a method that belongs to a wrong object.

4.3. Finally statement

  

4.4. Exception Simple test
1 Packagecn.javastudy.summary; 2 3ImportJava.io.FileInputStream; 4Importjava.io.FileNotFoundException; 5Importjava.io.IOException; 6 7 Public classTestException {8 9/**10 * There is a simple notation for any method that throws out an exception that can be handled: "Throws Exception", 11 * Because the Exception class is the base class for all of the exception classes that can be handled, throwing the Exception class throws all that can be In the abnormal class of the manager. 12 * After using "throws Exception" to throw all the exceptions that can be handled, these thrown exceptions are given to the Java Runtime System for processing, and 13 * are handled by printing out all the associated error stack information for these exceptions. *@throwsException*/16voidFN ()throwsException {17 18     } 19 20/**21 * After knowing the type of the exception, the method declaration uses throws to throw out the exception@paramI *@throwsArithmeticException*/25voidM1 (intIthrowsArithmeticException {26 27     } 28 29voidM2 (inti) {30if(i = = 0) { 31//This is done by manually throwing the exception, using "Throw+new exception object" to throw the exception object. 32//here is a new exception object, when constructing this object can also specify his relevant information, as indicated here the exception information "I cannot equal to 0"33//when this object is thrown, the GetMessage () method is used to get the message "I cannot equal 0". 34Throw NewArithmeticException ("I cannot be equal to 0"); 35         } 36     } 37 38/**39 * Under normal circumstances if you do not write the Try......catch statement then the program will be compiled error, 40 * because there may be two of the exceptions that must be handled: FileNotFoundException and IOException. 41 * But due to the use of throws to declare the method F (), we have thrown the two possible exceptions, 42 * So it is not possible to write Try......catch statements to deal with the exceptions that might be generated. The * f () method takes the thrown exception to the next method to invoke it to process the@throwsFileNotFoundException *@throwsIOException*/47voidF ()throwsFileNotFoundException, IOException {48//There may be filenotfoundexception anomalies here .FileInputStream FIS =NewFileInputStream ("MyFile.txt"); 50//There may be ioexception anomalies here .51intb =Fis.read ();52 while(b! =-1) { System.out.println (Char) b); The B =Fis.read ();55         } 56     } 57 58/**59 * When calling the F () method inside the F2 () method, you must handle the exception thrown by the F () method, 60 * Of course, if the F2 () method does not handle the exception thrown by the F () method, then the F2 () method can also use throws to throw the exception, 61 * Give the next call to the F2 () method to handle the exception thrown by the F () method. 62 * Here F2 () call the F () method, choose not to handle the exceptions that may be thrown in the F () method, and continue to throw the exception .@throwsException*/65voidF2 ()throwsException {66f ();67     } 68 69/**The F3 method calls the F method to capture the 2 exceptions thrown by the F () method and to process the*/72voidF3 () {73Try { 74f ();75}Catch(FileNotFoundException e) {System.out.println (E.getmessage ());//the way to handle this is to print out the error message.77}Catch(IOException e) {E.printstacktrace ();//the process is to print out all the wrong stack information using the Printstacktrace () method. 79         } 80     } 81 82 Public Static voidMain (string[] args) {FileInputStream FIS =NULL; 84Try { FIS =NewFileInputStream ("MyFile.txt"); 86intb = Fis.read ();//this has the potential to throw IOException exceptions .87 while(b! =-1) { System.out.println ((Char) b); The B =Fis.read ();90             } 91}Catch(FileNotFoundException e) {92//use catch to catch the exception object E of the FileNotFoundException class exception. And let the exception object E itself call the Printstacktrace method to print out all the error messages93e.printstacktrace ();94}Catch(IOException e) {95//use catch again to capture the exception object E of the IOException class and have the exception object E call the GetMessage () method itself to print out the error message. 96System.out.println (E.getmessage ());;97}finally{ 98Try { 99/**100 * A file has been opened in the front, regardless of whether there is an error when opening this file, that is, there is no exception, and finally must be closed, 101 * So use the finally statement, in the FI Nally statement inside regardless of whether the previous file opened with an exception, in the finally execution In.close () will be able to shut down the file, 102 * Close the file may also produce an exception, so in finally also used the TRY......CATC H statement to catch an exception that is likely to occur. 103*/104fis.close ();105}Catch(IOException e) {106e.printstacktrace ();107             }108         }109     }110}

V. Declaring and Throwing exceptions

Vi. Use of custom exceptions

  

6.1. Custom exceptions
1 Packagecn.javastudy.summary;2 3/**4 * A custom exception class MyException, and is inherited from the Exception Class 5*/6 Public classMyExceptionextendsException {7 8Private intID;9 10/**11 * How to construct a custom exception class@paramMessage13 *@paramId14*/15 PublicMyException (String message,intID) {16Super(message);//constructor method for calling parent class exception17 This. ID =ID;18     }19 20/**21 * Code to get exception *@return at*/24 Public intgetId () {25returnID;26     }27 28}

6.2. Custom Exception Testing
1 Packagecn.javastudy.summary;2 3ImportJava.text.MessageFormat;4 5 Public classtestmyexception {6 7//throws MyException, throws the exception of our custom MyException class. 8 Public voidRegist (intNumthrowsMyException {9if(Num < 0) {10//use throw to manually throw an exception object for the MyException class. 11Throw NewMyException ("Negative numbers, unreasonable", 1);12         }13/**14 * Note: When we throw an exception, the System.out.println (Messageformat.format ("registered number: {0}", num)) will not be executed. 16 * When an exception is thrown, the entire method's call ends. -*/System.out.println (Messageformat.format ("registered persons: {0}"), num));19     }20 21 Public voidManage () {22Try {Regist (-100);24}Catch(MyException e) {SYSTEM.OUT.PRINTLN ("Registration failed, error code:" +E.getid ());26e.printstacktrace ();27         }System.out.println ("End of Operation");29     }30 31 32 Public Static voidMain (string[] args) {Testmyexception T =Newtestmyexception ();34t.manage ();35     }36 37}

Test results:

  

Vii. Summary of exception handling

  

Develop good programming habits, do not take the wrong to devour (that is, catch the exception after the practice of not making corresponding treatment, this practice is tantamount to hide the error, but the actual error is still there), do not easily throw the wrong, can deal with must deal with, can not handle must be thrown out. There are two ways to throw out, one is that after you know the type of the exception, the method declaration uses throws to throw the exception out, and the other is to manually throw it out, using the "throw+ exception object" You are the equivalent of throwing the exception object, and then write the exception that you want to throw in the declaration of the method.

Java Basic Learning Summary-Exception handling

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.