First, Java exception Summary:
Exception is when the program is running abnormal operation
1. Origin of the anomaly:
Describe the problems in the real world through the form of Java classes and block them into objects
In fact, Java is the description of the object after the abnormal embodiment
2. There are two types of problems: one is a serious problem, the other is a problem that is not serious.
For serious, Java uses the error class to describe
For error generally do not write targeted code to deal with it
For non critical, Java is described by the exception class
Exception can be handled using a targeted approach
3. Common exceptions are: array angle-crossing anomaly, NULL pointer exception ...
4. Regardless of error or exception have some common content.
For example: The news of the abnormal situation, causes and so on.
Throwable//Parent class (the same common features extracted from the following two classes)
|--error
|--excption//Two subclasses (which define many problems (anomalies))/* Parent class name is a subclass suffix * *
Instance 1: Example of an exception occurred
Class Demo
{public
int div (int x,int y)
{return
x/y
}
} Class Exceptiondemo
{public
static void Main (String args[])
{
Demo d=new demo ();
int X=d.div (4,0); 0 as Divisor
System.out.println ("x=" +x);
System.out.println ("over");
}
Run Result:
Exception in thread ' main ' java.lang.ArithmeticException:/by Zero
At Demo.div (exceptiondemo.java:5)
At Exceptiondemo.main (exceptiondemo.java:15)
From the results above, we can analyze that there are exceptions in lines 5th and 15th, because the mechanism of division is that the divisor cannot be 0, and then the operation throws an exception.
Instance 2: Exception example 2, memory overflow
Class Demo
{public
int div (int x,int y)
{return
x/y
}
} Class Exceptiondemo
{public
static void Main (String args[])
{
/*demo d=new Demo ();
int X=d.div (4,0);
System.out.println ("x=" +x);
System.out.println ("over");
* *
byte[] arr=new byte[1024*1024*1000];
}
Run Result:
Exception in thread "main" Java.lang.OutOfMemoryError:Java heap
At Exceptiondemo.main (exceptiondemo.java:19)
Java.lang.OutOfMemoryError: Represents a memory overflow exception
Ii. Handling of exceptions:
For exception handling, Java provides a unique statement for processing
Format
Try
{
Code that needs to be detected;
}
Catch
{
The code that handles the exception (how to handle it)
}
Finally
{
Code that must be executed;
}
Example 1: Demo Try Catch statement
Class Demo
{public
int div (int x,int y)
{return
x/y
}
} 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)
{
System.out.println ("incorrect divisor");
}
System.out.println ("over");
/*byte[] arr=new byte[1024*1024*1000];*/
}
}
Run Result:
Wrong divisor.
Over
Result Analysis: When the program is running, when the statement to Division is executed: return x/y, the object New Aritchmeticexception () of the exception is generated, and the try statement captures the object with the parameters of the catch statement
Exception e =new aritchmeticexception ();
After running the catch's processing statement, the problem is processed, end statement, output over
Example 2: Common method Action on caught exception objects (method of parent Throwable)
String GetMessage (); Get exception information
ToString ()//Return exception name: Exception information
Printstacktrace ()//Output exception name, exception information, where the exception appears
Class Demo
{public
int div (int x,int y)
{return
x/y
}
} 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)
{
System.out.println ("incorrect divisor");
Obtain exception information
System.out.println (E.getmessage ());
Get exception information, exception name
System.out.println (e.tostring ());
Output exception name, exception information, where the exception appears
E.printstacktrace ();
}
System.out.println ("over");
/*byte[] arr=new byte[1024*1024*1000];*/
}
}
Run Result:
Wrong divisor.
/by Zero
java.lang.ArithmeticException:/by Zero
java.lang.ArithmeticException:/by Zero
At Demo.div (exceptiondemo.java:5)
At Exceptiondemo.main (exceptiondemo.java:17)
Over
From the analysis of running results, the JVM default exception handling mechanism is to invoke the Printstacktrace method.
Instance 3: Two ways to handle throwing exceptions
1. Throw to JVM virtual machine processing
2. Throw the exception handle yourself
Class Demo
{public
int div (int x,int y) throws Exception/ * Throw an exception where there is a possible exception
/{return
x/y;
}
}
Class Exceptiondemo
{public
static void Main (String args[])
{
Demo d=new demo ();
int X=d.div (4,0);
System.out.println ("x=" +x);
System.out.println ("over");
}
Run Result:
EXCEPTIONDEMO.JAVA:15: Error: Unreported exception error exception; It must be captured or declared to
then throw
int X=d.div (4,0);
^
1 errors
Result Analysis: This is because there is no handling of possible exceptions
Handling Mode 1: Constantly throwing exceptions, let the JVM virtual machine handle itself
Class Demo
{public
int div (int x,int y) throws Exception/ * Throw an exception where there is a possible exception
/{return
x/y;
}
}
Class Exceptiondemo
{public
static void Main (String args[]) throws Exception/ * continues to throw an exception to the virtual machine * *
{
Demo d=new demo ();
int X=d.div (4,0);
System.out.println ("x=" +x);
System.out.println ("over");
}
Treatment Mode 2: Handle the exception yourself
Class Demo
{public
int div (int x,int y) throws Exception/ * Throw an exception where there is a possible exception
/{return
x/y;
}
}
class Exceptiondemo
{public
static void Main (String args[])
{
Demo d=new demo ();
Try //Handle exception
{
int x=d.div (4,0);
System.out.println ("x=" +x);
}
catch (Exception e)
{
System.out.println ("incorrect divisor");
Get exception information, exception name
System.out.println (e.tostring ());
System.out.println ("Over");}}
Summarize:
Declare an exception on a function. Easy to improve security, let the call place for processing, do not handle the compilation failed.
Example 4: For multiple exception handling
1. When declaring an exception, it is recommended to declare a more specific exception so that it can be handled more specifically
2. Declaring a few exceptions, it corresponds to a few catch blocks, and do not define extra catch fast.
If the exception in multiple catch blocks has an inheritance relationship, the parent class exception catch block is placed below.
Class Demo
{public
int div (int x,int y) throws Arithmeticexception,arrayindexoutofboundsexception
{
int arr[]=new int [x];
System.out.println (Arr[4]);
Return x/y
}
}
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 (ArithmeticException E)/ * Division Law Exception object received, the first execution * *
{
System.out.println ("divisor error");
Get exception information, exception name
System.out.println (e.tostring ());
System.out.println ("over");
}
catch (ArrayIndexOutOfBoundsException E)/ * data out of bounds to receive, the second execution * *
{
System.out.println ("Array Out of Bounds");
Output exception information
System.out.println (e.tostring ());
}
catch (Exception E)// parent class Exception receive, finally execute, recommend not to write this, let the program terminate
///////* Use polymorphic/* SYSTEM.OUT.PRINTLN (e.tostring ());
}
}
}
Run Result:
Array out of bounds.
Java.lang.arrayindexoutofboundsexception:4
Suggestions:
In catch processing, it is important to define the specific handling
Do not simply define a sentence e.printstacktrace ().
And don't simply write an output statement
Because users can not understand, it is best to save to the file, regularly sent to our developers to view.
Instance 5: Custom exception
Have you noticed that the exceptions we are using are encapsulated in Java
But in actual development, the exception that appears in our program, may be Java is not encapsulated,
This time, you need to define your own
According to the above code, I define the divisor cannot be negative, the code is as follows
Class Demo
{public
int div (int x,int y) throws Fushuexception/ * Throws an exception *
/{if (y<0)
{
throw new Fushuexception ("The denominator appears negative------/bu Fushu", y); /* You manually throw the exception object
/} return
x/y
}
}
Class Fushuexception extends Exception
{
private int value;
Fushuexception (String m,int value)
{
super (m); /* Pass parameters to the parent-class exception GetMessage method * *
this.value=value;
}
public int GetValue ()/ * Custom method, returns a negative number */
{return
value;
}
}
Class Exceptiondemo
{public
static void Main (String args[])
{
Demo d=new demo ();
Try
{
int x=d.div (4,-3);
System.out.println ("x=" +x);
}
catch (Fushuexception E)/ * Catch Exception object/
{System.out.println (E.getmessage () +e.getvalue ()
)
;
System.out.println ("over");
}
Run Result:
The denominator appears negative------/bu FuShu-3
Over
From the above results, you can see
In this program, the divisor is-3, also considered to be wrong, is not operational.
Then you need to make a custom description of the problem.
When a throw throws an exception object inside the function, it must give the corresponding processing action.
Either within the internal try catch processing.
Either declare it on the function to be handled by the caller.
In general , an exception is found within a function, and a declaration is required on the function.
found that only the name of the exception is in the printed result, but there is no exception information.
Because the custom exception does not define the information.
How do you define exception information?
Because the operation of the exception information has been completed in the parent class.
So as soon as the subclass is constructed, the exception information is passed to the parent class through the Super statement.
You can then get custom exception information directly from the GetMessage method.
Custom exceptions must be custom classes that inherit exception.
Inheritance exception Reason:
The anomaly system has one feature: because both the exception class and the exception object are thrown.
They are all capable of being parabolic. This throwable is a unique feature of this system.
Only the classes and objects in this system can be manipulated by throws and throw.
The difference between throws and throw
Throws is used on functions.
Throw is used within functions.
The exception class followed by the throws. can be with multiple. separated by commas.
Throw is followed by an exception object.
There is a special subclass exception RuntimeException runtime exception in instance 6:exception
If this exception is thrown in the function content, the function can be passed without declaring that it is compiled.
If the exception is declared on a function, the caller can do so without processing, like compiling through the
The reason why you do not use the function declaration is that you do not need to let the caller handle
When this exception occurs, you want the program to stop because, at run time, there is a situation that cannot be run, and you want the program to stop
The programmer modifies the code.
Class Demo
{public
int div (int x,int y) throws Fushuexception/ * Throw the same result all the same * *
{
if (y<0)
{
throw new Fushuexception ("The denominator appears negative------/bu Fushu", y);
}
Return x/y
}
}
Class Fushuexception extends RuntimeException /* Inheritance runtimeexception*/
{
fushuexception (String m,int Value)
{
super (M);
}
}
Class Exceptiondemo
{public
static void Main (String args[])
{
Demo d=new demo ();
int X=d.div (4,-3); /* Run to this will appear exception, compile no problem
/System.out.println ("x=" +x);
System.out.println ("over");
}
Run Result:
Exception in thread "main" fushuexception: the denominator appears negative------/bu Fushu
At Demo.div (exceptiondemo.java:7)
At Exceptiondemo.main (exceptiondemo.java:26)
From the results above you can see:
When customizing an exception: If the exception occurs, the operation cannot continue.
Let the custom exception inherit runtimeexception.
There are two types of exceptions:
1, the exception that was detected at compile time.
2, an exception that is not detected at compile time (Run-time exception). RuntimeException and its subclasses)
The above comprehensive understanding of the exception handling mechanism in Java is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.