1. Overview of Exceptions
exception : The abnormal behavior that occurs when the program is running
The origin of the
anomaly : The problem is also a specific thing in real life, can also be described by the Java class, and encapsulated into objects
In fact, Java is the object of the description after the abnormal situation
Simple: Exception: Encapsulate the program as an object.
The division of the
problem : Two kinds: One is a serious problem, a kind of non-serious problem
For serious Java by the error class to describe
Do not write real code for error handling
For non-critical, Java is described by the exception class
For exception can be handled with a targeted approach
Both error and exception have some common content
For example: abnormal information, causes of the cause and so on.
Throwable
|--error
|--exception
2. Exception handling
Java provides a unique statement to handle
Try
{
Code that needs to be detected;
}
catch (Exception class variable)
{
Code to handle exception (processing mode)
}
Finally
{
Statements that are bound to execute
}
3. Common methods for capturing the exception objects are:String getmessage (); Get exception information
class {int div (int a,intb) throws Exception//function with a throws keyword life it may cause problems {return A/b;}} Class Exceptiondemo {public static void main (string[] args) {demo d=new demo (); Try{int x=d.div (4,0); System.out.println ("x=" +x); catch (Exception e)//exception e=new arithmeticexception (); {System.out.println ("except 0)"; System.out.println (E.getmessage ());// /by zeroSystem.out.println (e.tostring ());// Exception Name: Exception information e.printstacktrace ();//exception name, exception information, where the exception occurred//In fact, the JVM default exception handling mechanism, is to call the Printstacktrace method//Print exception tracking information} System.out.println ("Over");}}
4, declare the exception on the function.Facilitates security, allows the caller to process or continue to throw, and does not handle compilation failures.
5, the treatment of multiple anomalies
- When declaring exceptions, it is recommended to declare more specific exceptions so that the processing can be more specific
- The other side declares that several exceptions have several catch blocks, and do not define redundant catch blocks
- If an inheritance relationship occurs in multiple catch, the exception catch block of the parent class is placed at the bottom
- It is recommended that in catch processing, you must define the specific handling method
- Do not simply define a sentence, e.printstacktack ();
- Also do not simply output a statement on the screen
- Exception Log File
Class Demo{int div (int a,intb) throws Arithmeticexception,arrayindexoutofboundsexception// function through a throws keyword life of this feature may cause problems {int[] arr=new int[a]; System.out.println (Arr[4]); return a/b;}} Class ExceptionDemo1 {public static void main (string[] args)//throws Exception{demo d=new Demo (); Try{int x=d.div (4,0); System.out.println ("x=" +x); catch (ArithmeticException e) {System.out.println (e.tostring ()); System.out.println ("was 0 apart! ");} catch (ArrayIndexOutOfBoundsException e) {System.out.println (e.tostring ()); System.out.println ("The horn is out of bounds!") ");} catch (Exception e) {}/**/system.out.println ("over");}}
6. Custom Exceptions:
Because there are some unique problems in the project that are not described and encapsulated by Java, all of these specific problems can be encapsulated in a custom exception, in accordance with the concept of Java's encapsulation of the problem.
Requirements: In this program, for the out of the book is-1, also considered to be wrong is unable to calculate
Then you need to have a custom description of the problem
When there is a throw exception object inside the function, the corresponding processing action must be given.
Or in-house try Catch processing
It is either declared on the function to let the caller handle
In general, there is an exception in the function that needs to be declared on the function.
Found only the name of the exception in the print result, but no information about the exception, because the custom exception does not define the information
7, how to define the exception information?
Because the operation of the exception information has already been
completed in the parent class,
All subclasses, as long as they are constructed, pass the exception statement to the parent class, through the Super statement,
You can get custom exception information directly from the GetMessage () method
Custom Exceptions:
Must be a custom class to inherit exception.
8, inherit exception reason?
The exception system has one feature: because both the exception class and the exception object are thrown,
They all have the ability to be parabolic, which is a unique feature of the Throwable system,
Only classes and objects in this system can be manipulated by throws and throw
9. The difference between throws and throw:
throws used on a function
Throw is used within a function
Throws followed by the exception class, you can follow multiple, separated by commas
Throw is followed by an exception object
Class Fushuexception extends Exception //getmessage () {/*private String msg; Fushuexception (String msg) {this msg=mag;} Public String GetMessage () {return msg;} */private int value; Fushuexception () {}fushuexception (String msg,int value) {super (msg); this.value=value;} public int GetValue () {return value;}} Class Demo{int div (int a,intb) throws Fushuexception{if (b<0) {throw new Fushuexception ("There is a case where divisor is negative", b);// Manually throwing a custom exception object through the Throw keyword}return A/b;}} Class ExceptionDemo3 {public static void main (string[] args) {demo d=new demo (); Try{int x=d.div (4,0); System.out.println ("x=" +x); catch (Fushuexception e) {System.out.println (e.tostring ());//system.out.println ("divisor appears negative"); SYSTEM.OUT.PRINTLN ("The negative number of the error is---" +e.getvalue ());} System.out.println ("Over");}}
10. Abnormal Practice
computer programming, start thinking about problems in class.
For example, the problem is: Computer blue screen
computer Smoke
to describe the problem encapsulated as an object,
Can be appropriate smoke occurs after the lecture progress can not continue
the problem of the computer turned into a problem of the lecturer in the ——————, the lesson plan could not be completed.
Class Lanpingexception extends Exception{lanpingexception (String message) {super (massage)}}class maoyanexception Extends Exception{maoyanexception (String message) {super (massage);}} Class Noplanexception extends Exception{noplanexception (String msg) {super (MSG);}} class Computer {private int state=1;//represents normal state public void Run () throw lanpingexception,maoyanexception {if (state==2) throw New Lanpingexception ("blue screen"), if (state==3) throw new Maoyanexception ("Smoke"); SYSTEM.OUT.PRINTLN ("Computer Run");} public void Reset () {state=1; SYSTEM.OUT.PRINTLN ("computer restart"); run ();}} Class Teacher{private String name;private computer copt; Teacher (String name) {this.name=name;cmpt=new computer ();} public void Prelect () throws Noplanexception{try{cmpt.run ();} catch (Lanpingexception e) {cmpt.reset ();} catch (Maoyanexception e) {test (); throw new Noplanexception ("Class cannot Continue" +e.getmessage ());} System.out.println ("Lecture");} public void Test () {System.out.println ("practice");}} Class Exceptiontest{public static void Main (string[] args) {Teacher t=new Teacher ("Mr. Bi"); Try{t.prelect ();} catch (Noplanexception e) {System.out.println (e.tostring ()); System.out.println ("Change teacher or Holiday");}} /*finally code block: Defining code that must be executed is typically used to close a resource */
11. Exception Handling Problem format
First format: Try{}catch () {}finally{} The second format: Try{}catch () {} The third format: Try{}fianally{}//catch is handling exceptions, if no catch means that the exception is not handled,// If the exception is detected at the time of the exception, then it must be declared that//finally is typically used to "close the resource" class Demo{public void Method () {throw new Exception ();} finally{//"Close Resource"}}
12, the exception in the sub-parent class coverage reflected
1. When a subclass overrides a parent class, if the method of the parent class throws an exception, the subclass's overriding method can only throw the exception of the parent class or the subclass of the exception.
2. If the parent throws more than one exception, the child class can only throw a subset of the parent exception when overriding the method of the parent class.
3, if there is no exception thrown in the Fred method, then the subclass can not throw an exception when overriding the method,
If a subclass method has an exception, try processing must be done, absolutely not thrown
Class Aexception{}class Bexception extends Aexception{}class cexception {}class fu{void Show () throws Aexception // Or bexception, it must not be cexception {}}class Zi extends fu{void show () throws aexception{}}
13. Summary of anomalies
what is an exception? Is the description of the problem, the problem is encapsulated in the object
--------------------------------------------------------------------------
Anomaly System:
Throwable
|--error
|--exception
|--runtimeexception
characteristics of the anomaly system: All classes in the exception system, as well as the objects created, have the ability to throw
In other words, the throws keyword can be manipulated by the throw.
Only the anomaly system has this feature
---------------------------------------------------------------------------------
throw and throws usage:
Throw is defined inside a function to throw an exception object
Throws is defined on a function, used to throw an exception class, can be thrown multiple, separated by commas.
A try process is not performed when the function content has an object thrown by a throw. Must be declared on the function, or the compilation fails
Note: Except for runtimeexception exceptions, that is, if a RuntimeException exception is thrown inside a function, the function is not declared
-------------------------------------------------------------------------------------
If the function declares an exception, the caller needs to process it, handle it, throw it, try
There are two types of exceptions:
Exception detected at compile time
If the exception is not processed at compile time (no throw, no try), then the compilation fails
The exception is identified, which means that this can be handled
Run-time exception (not detected at compile time)
At compile time, no processing is required and the compiler does not check
This exception occurs, it is recommended not to process, let the program stop, need to fix the code
---------------------------------------------------------------------------------------
Exception Handling Statements
Try
{
Code that needs to be detected;
}
catch ()
{
The code that handles the exception;
}
Finally
{
Code that is bound to execute;
}
There are three ways of bonding
The first type:
Try
{
}
catch ()
{
}
The second type:
Try
{
}
Finally
{
}
The third type:
Try
{
}
catch ()
{
}
Finally
{
}
Note:
1. Finally, the resource code is usually closed because the resource must be released
2, finally only one situation will not be executed, when executed to System.exit (0), finally will not execute
--------------------
------------------------------------------------------------
Custom Exceptions:
Define class inheritance exception or RuntimeException
1, in order to let the custom class has the parabolic
2, let the class have the method of operation exception
When you want to define custom exception information, you can use features that are already defined by the parent class
Exception information passed to the constructor of the parent class
Class MyException extends Exception
{
MyException (String message)
{
Super (message);
}
}
Custom exceptions: Encapsulate specific issues that arise in your program according to Java's object-oriented thinking
---------------------------------------------------------------------------------------
The benefits of exceptions:
1. Encapsulate the problem
2, the normal process code and problem-handling code to separate, easy to read
----------------------------------------------------------------------------------------
Exception handling principles:
1. Two kinds of processing methods: try or throw
2, call to the exception function, throw a few on the processing of several.
A try corresponds to multiple catch cases
3, multiple catch, the parent class catch to the bottom
4, catch within the need to define the targeted processing, do not simply define prinstacktrace, output statements
Don't even write it.
You can continue to throw in catch when this function is not handled by the caught exception
Try
{
throw new Aexception ();
}
catch (Aexception e)
{
Throw e;
}
If the exception is not handled, but does not belong to the exception that is present in the feature,
You can convert an exception and then throw that feature-related exception
Or an exception can be handled when it is necessary to provide an exception-related problem with this function,
When the caller knows and processes the exception, it can also convert the new exception after the replenishment is handled
Try
{
throw new Aexception ();
}
catch (Aexception e)
{
Handling of Aexception
throw new Bexception ();
}
Example: Remittance examples
-------------------------------------------------------------------------------------------------
Exception Considerations
When the child parent class overrides:
1. The exception that the subclass throws must be a subclass or subset of the parent class exception
2, if the parent class or interface does not throw an exception, the subclass overrides the exception, can only try not to throw
See:
Exceptiontest.java Teacher uses the computer class
Exceptiontest1.java The area of the graph
Java exception System, classification, capture, processing, customization