Java Exception Handling

Source: Internet
Author: User
Tags finally block getmessage instance method throw exception throwable try catch

Tag:note   style    and     avoid     cause     except   throwable   content   bounds   

Five, anomaly   anomaly Concept summary:  Exercise one: Abnormal system     problem:   1. Please describe the exception inheritance system    2. Please describe your understanding    3 of errors (Error). Please describe your understanding of the anomaly (expection)    4. Please describe your understanding of runtime Exceptions (runtimeexception)     :    1. Exception inheritance system is: The root class of the exception is Java.lang.Throwable, under which there are two sub-classes:   java.lang.error and java.util.Exception. And exception is divided into compile time exception: checked exception, and runtime exception: Runtime exception.     2.error: Represents an uncorrectable, malignant error that can only be generated by modifying code to circumvent errors, usually at the system level, so it is very serious.    3.exception: Represents a repairable benign (relative to error) exception that the programmer can and should correct by way of code to keep the program running, which must be handled.    4. Run-time exception: Runtime exception. During run time, check for exceptions. During compile time, run exception will not be detected by compiler (no error).    Practice II: The difference between throw and throws     problem:   1. Please describe the use position of the throw and what the function is?   2. Please describe the use position of throws, what is the function of?     answer:  The  1.throw keyword is usually used in the method body and throws an exception object. The program stops immediately when it executes to the throw statement, and the statements after it are not executed. The    2.throws keyword is typically applied when declaring a method to specify an exception that might be thrown. Multiple exceptions can be separated with commas. When the method is called in the main function, if an exception occurs, the exception object is thrown at the method call.    Exercise Three: Handling exceptions     issues:      1. There are several ways of handling exceptions,?  &nbsP   2. Explains in detail how each of these methods handles exceptions     answer:   1. There are two ways to handle exceptions, namely, using throws and try...catch...finally   2. Throws used on the declaration of the method followed by the exception class name, is to throw the exception to the caller to handle    3.try...catch...finally is to catch the exception, self-processing, processing completed after the program can continue to run    a) A try code block is a code that may occur with an exception    b) a catch code block, which is the code that encounters an exception that handles the exception, and a finally code block is code that must be executed regardless of whether an exception occurred or not, to dispose of the resource.       Exercise IV: Common exceptions and causes     issues: Please list common exceptions and explain why.      Answer:   nullpointerexception: null pointer exception.     throws the exception when the app tries to use null where the object is required. For example: Call an instance method of a Null object, access the properties of a null object, evaluate the length of a null object, and so on.    arrayindexoutofboundsexception: Array index out of bounds exception.   This exception is thrown when the index value of an array is negative or greater than or equal to the size of the arrays.    arithmeticexception: Arithmetic operation exception.     In the process of dividing by 0 such an operation will be such an exception, for this anomaly, we will have to check their own procedures involved in the mathematical operation of the place, the formula is not inappropriate.    numberformatexception: Number format exception.   The exception is thrown when an attempt is made to convert a string to the specified number type, and the string does not satisfy the format required by the number type.    1. Exception:  
Introduction: Refers to the program in the course of execution, the occurrence of abnormal conditions, will eventually lead to the JVM's abnormal stop. In object-oriented programming languages such as Java, the exception itself is a class that creates an exception object and throws an exception object. The way Java handles exceptions is to interrupt processing
Notes
An exception is not a syntax error, a syntax error does not compile, a bytecode file is not generated, and it cannot be run at all.
① anomaly System: API:
anomaly mechanism is actually to help us find the problem in the program, the root of the exception is java.lang.Throwable, the following two sub-classes,-java.lang.error (engineers can not handle, can only be avoided)-ja Va.util.Exception (which can be avoided due to improper use) the usual anomaly is java.util.Exception
Common methods in ②throwable: ⑴ printing Exception details
Public
void Printstacktrace (): Contains the type of the exception, the reason for the exception, and the location where the exception occurred, in the development and debugging phase, you have to use Printstacktrace.
⑵ get the cause of the exception
Public
String GetMessage (): When prompted to the user, the reason for the error is prompted.
⑶ get exception type and exception description information (not necessary)
Public
String toString ():
Classification of ③ anomalies
⑴ Compile-time exception: checked exception. At compile time, the compilation fails (such as a date formatting exception) ⑵ runtime exception when the exception is not handled: Runtime exception. During runtime, check for exceptions at compile time, run exception will not be detected by compiler (no error) ( such as mathematical anomalies)
2. Handling Exceptions five key words: Try Catch finally throw throws
① Throw Exception throw
⑴ format:
throw new Exception class name (parameter)

⑵ throws an exception to tell the caller:

Step 1: Create an Exception object. Wrap up some hint information (the information can be written yourself) throw new NullPointerException ("The ARR array to access does not exist"); Step 2: Tell the caller to throw an exception object through throw, pass it to the caller, and end the execution of the current method
Example: public static void Main (string[] args) {
        int[] arr = {2,4,52,2} ;        INT index = 4;        int element = GetElement (arr, index);   & nbsp     System.out.println ("element =" + Element);        SYSTEM.OUT.PRINTLN ("over")  & nbsp;       }
        private static int getelement (int[] arr, int index) {       //Judging Index Whether to cross-border         if (index<0| | index>arr.length-1) {         //if out of bounds, the method cannot continue the operation        &N after executing the throw exception Bsp  //then ends the execution of the current method and informs the caller that the exception is required to resolve the           throw New ArrayIndexOutOfBoundsException ("Array Out of Bounds");       }        int element = Arr[index];          return element;       }      results:      & nbsp Exception in thread "main" Java.lang.ArrayIndexOutOfBoundsException: array out of bounds l~~~      at DemoThread.ThrowTest.getElement (throwtest.java:22)       at DemoThread.ThrowTest.main (Throwtest.java : 7)     ②objects non-null judgment
Remember that we have learned a class objects, once mentioned it is composed of some static practical methods, these methods are Null-save (null pointer security) or null-tolerant (tolerant of NULL pointers), then in its source code, the object is a null value   Throws an exception operation. public static <T> t Requirenonnull (t obj): view specifies that the reference object is not NULL.
public static <T> t Requirenonnull (t obj) {
if (obj = = null) throw new NullPointerException ();   return obj; }
③ Declaration Exception throws
Description: Identify the problem, report it to the caller, and if the method throws a compile-time exception through throw, without capturing processing, it must be declared with throws for the caller to handle. The keyword throws is used on a method declaration to indicate that the current method does not handle an exception, but rather to remind the caller of the method to handle the exception format: modifier return value type method name (parameter) throws exception class Name 1, exception class name 2 ... {}    
Example:
Public
static void Main (string[] args) throws FileNotFoundException {Read ("a.txt"); }//If there is a problem defining the function that needs to be reported to the caller, you can declare public static void read (String path) by using the throws keyword on the method throws Filenotfoundexcept ion{if (!path.equals ("A.txt")) {//Assume that if the file is not a.txt It is an error that is an exception throw throw new Filenotfoundexcepti      On ("File does not exist"); }     }        
④ catching exception Try Catch
Catch Exception: The exception-specific statement is captured in Java and can be handled in the specified manner for the occurrence of the exception
Format:
try{
//
Write code
}catch (Exception type E)
that may have an exception {The
code that handles the exception
//Can be log, print Constant information, continuing to throw exceptions
Try: The code block that writes the possible exception code catch: A catch that is used to perform some kind of exception, which is implemented to handle the caught exception
Example: public static void Main (string[] args) {try {
Read ("A12.txt");      }catch (FileNotFoundException e) {//Print exception e.printstacktrace (); } System.out.println ("over");
     }      private static void Read (String path) throws FileNotFoundException {      if (!path.equals ("A.txt")) {       throw new FileNotFoundException ("file does not exist");  & nbsp  }       /* if (!path.equals ("A.txt")) {       throw new IOException (); &nbsp ;      }*/      }         Capturing exceptions common methods:    Some viewing methods are defined in the Throwable class:      -public String getMessage (): Gets the description of the exception, the reason (when prompted to the user, the reason for the error.)       -public String toString (): Gets the type of the exception and the exception description information (not used).      -public void Printstacktrace (): Prints the trace stack information for the exception and outputs it to the console.        contains the type of exception, the cause of the exception, and the location where the exception occurred, both during the development and commissioning phase, using Printstacktrace.        In development you can also convert a compile-time exception to run-time exception handling in a catch.        Multiple exception usage capture what should I do with it?        1. Multiple exceptions are handled separately.       2. Multiple exceptions are captured once and processed more than once.     &NBSp 3. Multiple exceptions are captured once at a time.        Generally we use one capture multiple times,      format as follows:      try{          Writing code that might cause an exception        }catch (Exception type A E) {When a type exception occurs in try, the catch is used to capture .          Handling exception codes          //logging/Printing exception information/Continuation exception        }catch (exception type B e) { Use this catch to capture .          handling exception code          //Log/Print exception information when a B type exception occurs in try Continue to throw exceptions        }      notes:       NOTE: This exception handling method, Requires that exceptions in multiple catch cannot be the same,      and if there is a child parent exception relationship between multiple exceptions in a catch,      then the subclass exception requires the catch handling above,      Parent exception in the following catch processing  ⑤finally code block     Description:    There are some specific code that needs to be executed regardless of whether the exception occurred. Also, because exceptions cause program jumps, some statements do not.     Finally solves this problem, and the code stored in the finally code block is bound to be executed.     Open Some physical resources (such as disk File/network link/database link, etc.) we all have to close the open resource         usage:    try after useCatch finally: You need to handle the exception itself, and eventually you have to close the resource.         notes:      finally cannot be used alone.          example:        public static void main (string[] args) {    &nbs P Try {       read ("A11.txt");     }catch (FileNotFoundException e) {    &NBSP ;  e.printstacktrace ();     }finally {      &NBSP;SYSTEM.OUT.PRINTLN ("Whatever happens I want to do");      }      SYSTEM.OUT.PRINTLN ("over");     }       private static void Read (String path) throws FileNotFoundException {      if (!path.equals ("A.txt")) {&nbsp ;      throw New FileNotFoundException ("file does not exist!) ");     }     }   tips:    Only when you invoke the relevant method of exiting the JVM in a try or catch At this point the finally will not execute, otherwise finally will be executed far away            results:      No matter what I want to do     &NBsp Java.io.FileNotFoundException: file does not exist!       over       at DemoThread.finallyTest01.read (finallytest01.java:19)        at DemoThread.finallyTest01.main (finallytest01.java:8)      ⑥ Exception considerations    ⑴ runtime exception thrown can not be handled, neither capture nor declare throw    ⑵ if the parent throws multiple exceptions, the subclass overrides the parent class method, only throws the same exception or his subset    ⑶ the parent class method does not throw an exception, When the subclass overrides the parent class, the method also does not throw an exception, at which time the subclass produces the exception, can only capture processing, cannot declare throw    ⑷ when multiple exception handling, the front class cannot be the parent class of the class after the  ⑸ when try/ After a catch can host a finally block of code, where the code is bound to be executed, typically used for resource recycling    ⑹ If finally has a return statement, always returns the result in Finally, avoiding the situation     3. Custom exceptions   Descriptions:     Why custom exception classes are required:     different exception classes in Java, each of which represents a specific exception condition, There are always some anomalies in development where sun is not defined, and we define the exception class according to the exception of our business. , such as the problem of negative age, negative test scores.      In the above code, it is found that these exceptions are internal to the JDK, but there are many exceptions in the actual development, which are most likely not defined in the JDK, such as the problem of age negative, negative test scores. Can you define the exception yourself?      What is a custom exception class:     defining exception classes in development according to their own business exceptions .     Customizing a business logic exception: Loginexception. A login exception class.  &nbSp   How the Exception class defines:     1. Customize a compile-time exception: Customize the class and inherit from Java.lang.Exception.     2. Customize a runtime exception class: Custom class and Inherit from java.lang.runtimeexception   example:    public class Diyetest {    private static string[] names= {"Bill", "Hill", "Jill"};    public static void main (string[] args) {     //Simulation Login      try{     //code for possible exception       Checkusername ("Bill"); nbsp    //If not registered successfully       SYSTEM.OUT.PRINTLN ("registered successfully");      }catch ( Loginexception e) {      E.printstacktrace ();     }   }     private static Boolean Checkusername (String uname) throws Loginexception {     for (string name:names) {&NB Sp     if (Name.equals (uname)) {       //throws a login exception if the name is in it        throw New L Oginexception ("no login");     }    &NBSP;}&NBsp    return true;    }   }      class loginexception extends exception{    Public loginexception () {   }    /**     *     * @param name for exception hints      */    public loginexception (String name) {     &NBS P;super (name);   }   }  

<wiz_tmp_tag id= "Wiz-table-range-border" contenteditable= "false" style= "Display:none;" >



From for notes (Wiz)



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