Java Basics-Exception handling

Source: Internet
Author: User
Tags getmessage

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 package cn.javastudy.summary; 2 3 public class testex{4 5 public static void Main (String args[]) {6 int arr[]={1,2,3}; 7 Syst Em.out.println (arr[2]);                 8/** 9 * Here you use Try......catch to capture the exception generated by 0, whose basic format is: Ten * try{11 statements;//a statement that could produce an exception 12 ......                 }14 catch (Throwable-subclass e) {//exception parameter E15 statements;//exception handler 16 ...... }18 */19 try{20 System.out.println (arr[2]/0);}catch (arithmeticexcep tion AE) {//Here is the type declaration of this exception parameter, which declares what type of exception this exception belongs to System.out.println ("The system is being maintained, please later!") "); 23/**24 * Use the Printstacktrace () method to print out this wrong stack of information. 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 is also used in this way to print out the 30*/31 Ae.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 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 * There is a simple way for any method to throw out an exception that can be handled: "Throws Exception", 11 * 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. 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.      * @throws Exception * */void FN () throws Exception {17 18} 19 20/** 21 * After you know the type of the exception, the method declaration uses throws to throw the exception out of the way * @param i, @throws arithmeticexception * * M1 (int i             ) throws ArithmeticException {0}, void m2 (int i) {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, in the construction of this object can also specify his relevant information, as indicated here the exception information "I can not be equal to 0" 33//This object is thrown to use the GetMessage () method to get the "I cannot be equal to 0 "this information.        34     throw new ArithmeticException ("I cannot be equal to 0"); 35} 36} 37 38/** 39 * Normally if the Try......catch statement is not written here, the program compiles with an error, 40 * because there may be two exceptions that must be handled: Fi Lenotfoundexception 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 * @throws FileNotFoundException * @throws IOException 46 */47 void F () throws FileNotFoundException, IOException {48//here is a possible FileNotFoundException exception fileinputs Tream fis = new FileInputStream ("MyFile.txt"); 50//There may be a IOException exception in this case, an int b = Fis.read ();     while (b! =-1) {System.out.println ((char) b); n = 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 also has no way to handle the exception thrown by the F () method, the F2 () method can also use the T Hrows throws an exception, 61 * to 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 exception that may be thrown in the F () method, and continue to throw the exception 63      * @throws Exception */F2 () throws Exception {67} 68 69/** 70 * The F3 method calls the F method to capture the 2 exceptions thrown by the F () method and to process the seven */F3 void () {The. Ilenotfoundexception e) {System.out.println (E.getmessage ());//The method of processing is to print the error message out of the "C" catch (ioexcept Ion e) {e.printstacktrace ();//The method of processing is to use the Printstacktrace () method to print out all the wrong stack information.         ()-----} Bayi---------static void main (string[] args) {FileInputStream FIS = null; 84 try {fis = new FileInputStream ("MyFile.txt"), and the int b = Fis.read ();//This may be thrown ioexceptio              N Exception (b! =-1) {System.out.println ((char) b); } FileNotFoundException} catch (e) {92//use catch to Catch FileNotFoundException Class Exception exception object E. And let the exception object E call the Printstacktrace method itself to print out all the error messages. E.prinTstacktrace (); 94} catch (IOException e) {95//use catch to catch the exception object E of the IOException class again, and let the exception object E call the GetMessage () method itself to print out the error message. System.out.println (E.getmessage ()); }finally{98 try {99/**100 * has opened a file in front of it, regardless of whether an error occurred when opening the file, that is, there is no production Raw exception, you must finally close this file, 101 * Therefore using the finally statement, in the finally statement, regardless of whether the previous file opened in the case of an exception, the last here to execute In.close () will be able to shut down this file, 10 2 * Closing a file can also cause an exception, so the Try......catch statement is used in finally to catch a possible exception. 103 */104 Fis.close (); catch (IOException e) {106 E.prin Tstacktrace (); 107}108}109}110}
V. Declaring and Throwing exceptions

Vi. Use of custom exceptions

  

6.1. Custom exceptions
1 package cn.javastudy.summary; 2  3/** 4  * Custom Exception class MyException, inherited from Exception Class 5  */6 public class MyException extends Exception {7  8     private int id; 9     /**11      * How to construct a custom exception class *      * @param message13      * @param id14      */15     Public MyException (String message,int ID) {+         super (message);//constructor method for calling parent class exception         this.id = id;18     }19     /**21      * Get exception code in      * @return23 */24 public     int getId () {         id;26     }     28}
6.2. Custom Exception Testing
1 package cn.javastudy.summary; 2 3 Import Java.text.MessageFormat; 4 5 public class Testmyexception {6 7//throws myexception, throws 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 a Myexceptio The exception object for the N class. throw new MyException ("negative numbers, unreasonable", 1); 12}13/**14 * Note: When we throw an exception, the Ystem.out.println (Messageformat.format ("registered persons: {0}", num)), will not be executed. 16 * When an exception is thrown, the entire method's call ends. */18 System.out.println (Messageformat.format ("registered persons: {0}", num));}20 public void Manage () {try {regist (-100); catch (MyException e) {System.out.println ("Failed to register, error code:" +e.getid ()); E.printstack Trace ();}28 System.out.println ("End of Operation"),}30 public static void Main (string[] Ar GS) {testmyexception t = new testmyexception (); T.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 Basics-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.