005 Exception Handling

Source: Internet
Author: User
Java basics-Exception Handling I. Concept of exceptions

  An exception refers to an error occurred during the runtime, that is, an error occurred during the execution period after the execution of the program starts.. When an error occurs, it is most important to observe the name and row number of the error.

  

1 package CN. javastudy. summary; 2 3 Public class testex {4 5 public static void main (string ARGs []) {6 int arr [] = {1, 2, 3}; 7 system. out. println (ARR [2]); 8/** 9 * use try... here ...... Catch is used to capture exceptions generated by dividing by 0. The basic format is: 10 * try {11 statements; // The statement 12 that may cause exceptions ...... 13} 14 Catch (throwable-subclass e) {// exception parameter E15 statements; // exception handling program 16 ...... 17} 18 */19 try {20 system. out. println (ARR [2]/0); 21} catch (arithmeticexception AE) {// here is the type declaration of this exception parameter, which type of exception is declared? 22 system. out. println ("the system is being maintained. Please wait! "); 23/** 24 * here the incorrect stack information is printed using the printstacktrace () method. 25 * the so-called "error stack information" indicates that this error may be caused by the previous error. 26 * the previous error may be caused by another error. Which error is the cause? 27 * print out all the error messages. This kind of information can often prompt programmers for debugging errors. 28 * This information is very useful, so we often use this method to print out the error information. 29 * by default, the error message is printed in 30 */31 AE. printstacktrace (); 32} 33} 34}

Code running result:

  

Summary:

An exception is an error during running. After an error occurs during running, Java will first find the corresponding catch code to see if catch is used to catch the exception, if a catch exists, Java will automatically jump to the catch to handle the exception. If no catch exists, Java will throw the error and print the relevant error information. If you want to catch exceptions, you must write a try statement. If you do not try a catch, you cannot use a catch statement. If you try a catch, an exception may occur, in catch, exception handling occurs when the statements in try are run.

When declaring a method, you can specify the type of exception that may be thrown by this method. Throw is used to throw an exception. The possible exceptions declared by throws after declaring a method must be captured.

  

 

 

Ii. Exception Classification

  

 

Iii. Exception capture and handling

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

  

It is a good programming habit to handle exceptions after they are captured, even if the error information of the exception is printed out. If this error is not handled, it is to hide it quietly. However, this error still exists, but it cannot be seen. This is a very dangerous programming habit. It is absolutely impossible to do so. When an exception is caught, it must be handled. If it cannot be handled, it will throw the exception and let other methods handle it. In short, it is a very bad programming habit to avoid handling exceptions after they are caught.

When any method throws an exception that can be handled externally, there is a simple Syntax:"Throws Exception", Because the exception class is the root class of all Exception classes that can be processed, throwing the exception class will throw all the exception classes that can be processed. Use"Throws ExceptionAfter all the exceptions that can be handled are thrown, The thrown exceptions are handed over to the Java runtime system for processing, the solution is to print out all the error stack information related to these exceptions. In addition to testing, throwing an exception in the main method is a very bad programming habit. Try ...... Catch to catch the exception and handle the caught exception. The exception cannot be thrown directly in the main method to the system output during Java runtime. This is an irresponsible manifestation.If you want to write a program very robust, use try ...... Catch is an essential practice for capturing exceptions and handling caught exceptions.

4. Try... Cath... finally statement 4.1. Try statement

  

4.2. Catch statement

  

We usually use the printstacktrace () method to print the exception information. This method is used to print all the error information, including the information printed using the getmessage () method. Before using this method, you must create an error object before calling it. Because it is a method specific to an error object.

4.3. Finally statement

  

4. Simple exception Test
1 package CN. javastudy. summary; 2 3 Import Java. io. fileinputstream; 4 Import Java. io. filenotfoundexception; 5 import Java. io. ioexception; 6 7 public class testexception {8 9/** 10 * When any method throws an exception that can be handled externally, there is a simple Syntax: "throws exception ", 11 * because the exception class is the base class of all Exception classes that can be processed, throwing an exception class will throw all Exception classes that can be processed. 12 * after "throws exception" is used to throw all exceptions that can be handled, the thrown exceptions are handled by the Java runtime system, 13 * the solution is to print out all the error stack information related to these exceptions. 14 * @ throws exception 15 */16 void FN () throws exception {17 18} 19 20/** 21 * after knowing the exception type, when declaring the method, throws is used to throw the exception 22 * @ Param I 23 * @ throws arithmeticexception 24 */25 void M1 (int I) throws arithmeticexception {26 27} 28 29 void m2 (int I) {30 if (I = 0) {31 // This method throws an exception manually, you can use the "Throw + new exception object" to throw this exception object. 32 // here is a new exception object. When constructing this object, you can also specify its related information, for example, the exception information "I cannot be equal to 0" is specified here. 33 // when this object is thrown, the information obtained by using the getmessage () method is "I cannot be equal to 0. 34 throw new arithmeticexception ("I cannot be equal to 0"); 35} 36} 37 38/** 39 * normally if try ...... If a catch statement is used, an error is reported during program compilation. For example, there may be two exceptions that must be handled: filenotfoundexception and ioexception. 41 * However, because throws have been used to throw these two exceptions when declaring method F (), 42 * So try ...... Catch statements to handle possible exceptions. 43 * F () method hand over the thrown exception to the next method to call it to handle 44 * @ throws filenotfoundexception 45 * @ throws ioexception 46 */47 void F () throws filenotfoundexception, ioexception {48 // The filenotfoundexception may occur here. 49 fileinputstream Fi = new fileinputstream ("myfile.txt"); 50 // ioexception may occur here. 51 int B = FS. read (); 52 while (B! =-1) {53 system. out. println (char) B); 54 B = FCM. read (); 55} 56} 57 58/** 59 * when calling the F () method in the F2 () method, you must handle the exception thrown by the F () method, 60 * Of course, if the F2 () method cannot handle the exception thrown by the F () method, the F2 () method can also throw the exception using throws, 61 * give the next method that calls F2 () to handle the exception thrown by the F () method. 62 * When F2 () calls the F () method, select not to handle the exception that may be thrown in the F () method, continue to throw 63 * @ throws exception 64 */65 void F2 () throws exception {66 F (); 67} 68 69/** 70 * F3 method call f method capture 2 exceptions thrown by F () method and handle 71 */72 void F3 () {73 try {74 F (); 75} catch (filenotfoundexception e) {76 system. out. println (E. getmessage (); // the error message is printed out. 77} catch (ioexception e) {78 E. printstacktrace (); // you can use the printstacktrace () method to print out all the wrong stack information. 79} 80} 81 82 public static void main (string [] ARGs) {83 fileinputstream FD = NULL; 84 try {85 FD = new fileinputstream ("myfile.txt "); 86 int B = FCM. read (); // This may throw an ioexception 87 while (B! =-1) {88 system. out. println (char) B); 89 B = FCM. read (); 90} 91} catch (filenotfoundexception e) {92 // use catch to catch the exception Object E of the filenotfoundexception class. And let the exception Object E call the printstacktrace method to print all error messages 93 E. printstacktrace (); 94} catch (ioexception e) {95 // catch the exception Object E of the ioexception class again, and let the exception Object E call getmessage () by itself () method to print out the error message. 96 system. out. println (E. getmessage (); 97} a file has been opened before finally {98 try {99/** 100 *. No matter whether an error occurs when the file is opened or whether an exception occurs, in the end, you must close this file. 101 * therefore, the finally statement is used. In the finally statement, no matter whether an exception occurs when the file is opened, execute in. close () can close this file, 102 * closes the file may also cause exceptions, so try... is also used in finally ...... Catch statements to capture Possible exceptions. 103 */104 FCM. Close (); 105} catch (ioexception e) {106 E. printstacktrace (); 107} 108} 109} 110}
5. Declare and throw an exception

 

6. Custom exceptions

  

 

6.1. A custom exception occurs.
1 package CN. javastudy. summary; 2 3/** 4 * custom exception class myexception, which is inherited from the exception class 5 */6 public class myexception extends exception {7 8 private int ID; 9 10/** 11 * custom exception class construction method 12 * @ Param message13 * @ Param id14 */15 public myexception (string message, int ID) {16 super (Message); // call the constructor of the parent exception class 17 this. id = ID; 18} 19 20/** 21 * Get abnormal code 22 * @ return23 */24 public int GETID () {25 return ID; 26} 27 28}
. Custom exception Test
1 package CN. javastudy. Summary; 2 3 Import java. Text. messageformat; 4 5 public class testmyexception {6 7 // throws myexception, throwing the exception of our custom myexception class. 8 Public void regist (INT num) throws myexception {9 If (Num <0) {10 // use throw to manually throw an exception object of the myexception class. 11 throw new myexception ("the number of people is negative, unreasonable", 1); 12} 13/** 14 * Note: When an exception is thrown, 15 * system. out. println (messageformat. format ("Number of registrants: {0}", num); will not be executed. 16 * after an exception is thrown, the call to the entire method ends. 17 */18 system. out. println (messageformat. format ("registrants: {0}", num); 19} 20 21 public void manage () {22 try {23 regist (-100); 24} catch (myexception e) {25 system. out. println ("registration failed, error code:" + E. GETID (); 26 E. printstacktrace (); 27} 28 system. out. println ("operation ended"); 29} 30 31 32 public static void main (string [] ARGs) {33 testmyexception T = new testmyexception (); 34 t. manage (); 35} 36 37}

Test results:

  

VII. Exception Handling Summary

  

 

Develop good programming habits and do not swallow errors (that is, do not handle exceptions after capturing them). This practice is equivalent to hiding errors, but in fact, the error still exists). Do not easily throw an error out of the bucket. You must handle the error that can be handled. There are two methods for throwing an exception out. One is to use throws to throw the exception out after the exception type is known, and the other is to manually throw the exception out, when "Throw + exception object" is used, you throw the exception object and write the exception to be thrown in the method declaration.

005 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.