Exceptions to the Java learning Personal memo

Source: Internet
Author: User
Tags throwable try catch

Overview

Exception: is an abnormal condition that occurs during runtime.

In Java, the object is described and encapsulated in the form of a class.

A class that describes an unhealthy condition is called an exception class.

Used to combine normal process code and problem-handling code,
Now separate the normal process code from the problem-handling code to improve readability.

In fact, the exception is Java through object-oriented thinking to encapsulate the problem into an object.

The exception class is used to describe it.
Different problems are described in different classes.

There are many problems, which means that there are many classes described.
The anomaly system is formed by extracting its generality.

The final problem (abnormal) is divided into two major categories
Throwable: Whether it's an error or an exception, the problem should be thrown, let the caller know and handle it.
The characteristic of this system is that throwable and all its subclasses have parabolic properties.
What does it mean to be parabolic? How can we embody the parabolic nature?
In fact, through two key words to reflect.
Throws throw, all classes and objects that can be manipulated by these two keywords have a parabolic nature.
|--1. generally non-processing. Generally use error to indicate
Feature: Is the problem of severity thrown by the JVM.
This problem occurs in general and is not targeted. Modify the program directly.
|--2. Can be handled, usually expressed in exception.

The characteristics of the system:
The suffix of the subclass is suffixed with its parent name, and is highly readable.

Class Exceptiondemo  {public      static void Main (string[] args)      {          int[] arr = new int[3];          System.out.println (arr[3]);//compile through, run not through                    sleep ( -5);      }        public static void sleep (int time)      {          if (time<0)          {               //throws New Futime ();//In the case of negative times of the code, This object contains information such as the name of the problem, information, location, and so on.         }          System.out.println ("I sleep ..." +time);}  }  Class Futime  {  }

Throw throw of Exception object

Class Demo  {public      int method (int[] Arr,int index)      {          if (arr==null)          {              throw new NullPointerException ("The reference to the array cannot be empty!");          }          if (index>=arr.length)          {              throw new arrayindexoutofboundsexception ("The corner label of the array is out of bounds" +index), the custom exception information is thrown here.         }          if (index<0)          {              throw new arrayindexoutofboundsexception ("The angle of the array cannot be negative" +index), the custom exception information is thrown here.         }          return arr[index];      }  }    Class ExceptionDemo2  {public      static void Main (string[] args)      {          int[] arr = new int[3];            Demo d = new demo ();          int num = D.method (arr,30);          System.out.println ("num=" +num);          System.out.println ("over");      }  }  

Custom Exception & Exception class thrown throws

is a positive number for a corner mark is not present and can be represented by a corner mark.
for cases where the angle is negative, prepare to be represented by a negative-angle-mark exception.

Negative Angle label This exception is not defined in Java.
Then, according to the idea of creating Java exceptions, object-oriented, a negative-angle-label is customized and encapsulated as an object.

This custom problem description is called a custom exception.

Class Demo  {public      int method (int[] Arr,int index) throws Fushuindexexception  //indicates thrown.     {          if (arr==null)          {              throw new NullPointerException ("The reference to the array cannot be empty!");          }          if (index>=arr.length)          {              throw new arrayindexoutofboundsexception ("The corner label of the array is out of bounds" +index), the custom exception information is thrown here.         }          if (index<0)          {              throw new fushuindexexception ("The corner label of an array cannot be negative" +index);          return arr[index];      }  }    Class ExceptionDemo3  {public      static void Main (string[] args) throws Fushuindexexception      {          int[] arr = new Int[3];            Demo d = new demo ();          int num = D.method (null,30);          System.out.println ("num=" +num);          System.out.println ("over");      }  }  

Note: If you have a class called an exception class, you must inherit the exception system, because only subclasses called the exception System are eligible for throw,throws, which can be manipulated by two of keywords.

Class Fushuindexexception extends Exception  {      fushuindexexception ()      {}      fushuindexexception (String msg)      {          super (msg);      }  }  

Classification of exceptions :
1. The exception is detected at compile time: As long as the exception and its subclasses are, except for the special sub-class RuntimeException system
Once this problem occurs, it is hoped that it will be detected at compile time, so that the problem can be handled in a corresponding way.
Such problems can be dealt with in a targeted way.

2. No exception is detected at compile time (runtime exception): Is the runtimeexception in exception and its subclasses.
This problem does not allow the function to continue, the operation can not be carried out, more because of the caller's cause or caused by the internal state changes caused.
Then this problem is generally not handled, directly compiled through, at run time, let the caller call the program to force stop, let the caller to modify the code.

So when customizing exceptions, either inherit exception or inherit runtimeexception.

the difference between throws and throw
1. Throws is used on functions.
Throw is used within a function.
2. Throws throws an exception class that can be thrown multiple, separated by commas.
Throw throws an exception object.

Exception capture Trycatch

Catch form of exception handling:
This is how the exception can be dealt with in a targeted manner.

The specific format is:

Try {     code that requires an exception to be detected. } catch (Exception class variable)//This variable is used to receive the exception object that occurred. {     The code that handles the exception.} } finally {     
Class Demo {public int method (int[] Arr,int index) throws Fushuindexexception,nullpointerexception//indicates thrown.          {if (arr==null) {throw new NullPointerException ("No array entity");          } if (index<0) {throw new Fushuindexexception ("The corner label of an array cannot be negative" +index);      } return Arr[index]; }} class ExceptionDemo4 {public static void main (string[] args) throws Fushuindexexception {int[          ] arr = new INT[3];          Demo d = new demo ();                 try {int num = D.method (null,-30);          System.out.println ("num=" +num);          } catch (NullPointerException e) {System.out.println (e.tostring ()); } catch (Fushuindexexception e) {System.out.println ("message:" +e.getmessage ());  The corner label of an array cannot be a negative value System.out.println ("String:" +e.tostring ());           Fushuindexexception: The corner label of an array cannot be a negative value                 E.printstacktrace ();//JVM the default exception handling mechanism is the method that invokes the exception object.          SYSTEM.OUT.PRINTLN ("Negative angle MARK exception!!!!");      } System.out.println ("over"); }} class Fushuindexexception extends Exception {fushuindexexception () {} fushuindexexception (String      msg) {super (MSG); }  }

the principle of exception handling :
1. function Content If you throw an exception that needs to be detected, you must declare it on the function.
Otherwise, it must be captured within the function with Trycatch, otherwise the compilation fails.
2. If you call a function that declares an exception, either Trycatch or throws, or the compilation fails.
3. When to catch, when throws?
Functions can be resolved internally, with catch.
Can not solve, with throws to tell the caller, by the caller resolved.
4. If a function throws more than one exception, then the call must have a corresponding number of catch for the targeted processing.
Inside there are several exceptions that need to be detected, just throw a few exceptions, throw a few, catch one.

Finally code block

Class Demo  {public      int show (int index)      {          if (index<0)          {              throw new ArrayIndexOutOfBoundsException ("Corner mark out of bounds!!!");          }          int[] arr = new int[3];          return arr[index];      }  }    Class ExceptionDemo5  {public      static void Main (string[] args)      {          Demo d = new demo ();          Try          {              int num = d.show ( -3);              System.out.println ("num=" +num);          catch (arrayindexoutofboundsexception e)          {              System.out.println (e.tostring ());  Do not write output statements at the time of development.         }          Finally//is typically used to close (release) the resource          {              System.out.println ("finally");}      }}    

For example:
Connecting to a database
Inquire. Exception
Close connection

The try Catch finally code block combination features:

1. Try Catch finally

2. Try catch (multiple) when no necessary resources need to be freed, you can not define finally.

3. Try finally//must be declared with throws

void Show () throws Exception  {     try     {         throw new Exception ();     }     Finally     {     }}

Exception Considerations:
1. When a subclass overrides a parent class method, the method of the parent class throws an exception, and the method of the child class can only throw the exception of the parent class or the subclass of the exception.

Explain:

Class A extends Exception  {  }  class B extends A  {  }  class C extends Exception  {  }    Exception      |--a          |--b      |--c    class Fu  {      void Show () throws A      {}  }  class Zi Extends Fu  {      void Show () throws a or B  //is thrown here must be a subclass of the parent class exception or parent exception, so C      {}} cannot be thrown    

2. If the parent throws more than one exception, the child class can only throw a subset of the parent class exception.
Explanation: If the parent throws a B c D, then the subclass either throws a B, either throws C D, or throws a B C, or it can all be thrown, in short, it cannot be thrown like a B c D e. Simply put: Subclasses overriding the parent class can only throw exceptions or subclasses or subsets of the parent class.
Note: If the method of the parent class does not throw an exception, then the subclass must not be thrown when overridden, only try.

Exceptions to the Java learning Personal memo

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.