1. Java exception summary:
Exception means abnormal operation when the program is running
1. Origin of the exception:
The description of problems in real things through the form of java classes and sealed into an object
In fact, it is the object manifestation after Java describes abnormal situations.
2. There are two types of problems: one is serious problem, and the other is serious problem
For serious cases, java describes it through the Error class
Error is generally not written to process it.
For non-serious, java is described by the Exception class
For Exception, you can use targeted processing methods to handle it
3. Common exceptions include: array corner marker cross-border exceptions, null pointer exceptions...
4. Whether Error or Exception has some common content.
For example: abnormal news, causes, etc.
Throwable //Premium class (the following two classes are extracted from the same commonality)
|--Error
|--Excption //Two subclasses (there are many problems defined (exception occurs)) /*The parent class name is the subclass suffix name*/
Example 1: Example of exception occurrence
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"); }}Running results:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Demo.div(ExceptionDemo.java:5)
at ExceptionDemo.main(ExceptionDemo.java:15)
From the above results, we can analyze that an exception occurred in both lines 5 and 15. This is because the division mechanism, the divisor cannot be 0, and an exception will be thrown when the operation is run.
Example 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]; }}Running results:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at ExceptionDemo.main(ExceptionDemo.java:19)
java.lang.OutOfMemoryError: represents memory overflow exception
2. Exception handling:
For exception handling, Java provides unique statements for processing
Format
try
{
code that needs to be detected;
}
catch
{
Code for handling exceptions; (processing method)
}
Finally
{
Code that will definitely be executed; (processing method)
}
Example 1: Demonstrate 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("Divorceived divisor"); } System.out.println("over"); /*byte[] arr=new byte[1024*1024*1000];*/ }}Running results:
There is an error in the divisor
over
Results analysis: When the program is running, when the division statement is executed: return x/y, an exception object is generated. New ArchmeticException(), the try statement captures this object with the parameters of the catch statement.
Exception e = new ArchmeticException();
After running the catch processing statement, the problem is processed, the end statement is finished, and the output is over
Example 2: Perform common method operations on captured exception objects (the method of parent class Throwable)
String getMessage(); //Get exception information
toString() //Return exception name: exception information
printStackTrace() //Output exception name, exception information, location of exception occurrence
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("Divorceived divisor"); //Get exception information System.out.println(e.getMessage()); //Get exception information, exception name System.out.println(e.toString()); //Output exception name, exception information, location where the exception occurs e.printStackTrace(); } System.out.println("over"); /*byte[] arr=new byte[1024*1024*1000];*/ }}Running results:
There is an error in the 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 the running results, the default exception handling mechanism of jvm is actually calling the printStackTrace method.
Example 3: Two ways to handle exception throwing
1. Throw it to the jvm virtual machine for processing
2. Handle the thrown exceptions yourself
class Demo{ public int div(int x,int y)throws Exception /*Exception throws where exceptions may occur*/ { 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"); }}Running results:
ExceptionDemo.java:15: Error: Unreported Exception error Exception; it must be captured or declared for throwing
int x=d.div(4,0);
^
1 error
Results analysis: This is because no exceptions are processed
Processing method 1: Continuously throw exceptions and let the jvm virtual machine handle it itself
class Demo{ public int div(int x,int y)throws Exception /*Exception throws where exceptions may occur*/ { return x/y; }}class ExceptionDemo{ public static void main(String args[]) throws Exception /*Continue to throw exceptions and give to the virtual machine*/ { Demo d=new Demo(); int x=d.div(4,0); System.out.println("x="+x); System.out.println("over"); }}Handling method 2: Handle exceptions by yourself
class Demo{ public int div(int x,int y)throws Exception /*Exception throws where exceptions may occur*/ { return x/y; }}class ExceptionDemo{ public static void main(String args[]) { Demo d=new Demo(); try //handle the exception yourself{ int x=d.div(4,0); System.out.println("x="+x); } catch(Exception e) { System.out.println("Divorceived divisor"); //Get exception information, exception name System.out.println(e.toString()); System.out.println("over"); } }}Summarize:
Declare exceptions on functions. It is convenient to improve security, allowing the call source to be processed without processing compile failures.
Example 4: Handling multiple exceptions
1. When declaring exceptions, it is recommended to declare more specific exceptions, so that they can be handled more specifically.
2. Declare several exceptions, and there are several catch blocks. Do not define unnecessary catch fast.
If there are inheritance relationships in multiple catch blocks, 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) /*Divide the exception object is received, the first execution is */ { System.out.println("Divorceived divisor"); //Get exception information, exception name System.out.println(e.toString()); System.out.println("over"); } catch(ArrayIndexOutOfBoundsException e) /*Receive the object with data out of bounds, the second execution is */ { System.out.println("Arrayout"); //Output exception information System.out.println(e.toString()); } catch(Exception e) /*Receive the parent class Exception, and execute it in the end. It is recommended not to write this, let the program terminate */ /* Use polymorphism*/ { System.out.println(e.toString()); } }}Running results:
The array is out of bounds
java.lang.ArrayIndexOutOfBoundsException: 4
suggestion:
When processing catch, you must define specific processing methods in catch.
Don't simply define e.printStackTrace().
Don't just write an output statement
Because users can't understand it, it is best to save it in a file and send it to our developers to view it regularly.
Example 5: Custom exception
Have you noticed that the exceptions we are using are all encapsulated in Java
However, in actual development, the exceptions that appear in our program may be that Java is not encapsulated.
At this time, you need to define it yourself
According to the above code, I define that the divisor cannot be a negative number. The code is as follows
class Demo{ public int div(int x,int y)throws FuShuException /*Top an exception*/ { if(y<0) { throw new FuShuException("The denominator has a negative number ------/bu FuShu",y); /*The object that throws the exception manually*/ } return x/y; }}class FuShuException extends Exception{ private int value; FuShuException(String m,int value) { super(m); /*Pass parameters to the getMessage method of the parent class Exception*/ this.value=value; } public int getValue() /*Customized method, return 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"); }}Running results:
A negative number appears in the denominator-----/bu FuShu-3
over
From the above results, we can see
In this program, the divisor is -3, which is also considered to be wrong and cannot be performed.
Then you need to have a custom description of this problem.
When throwing an exception object inside the function appears, the corresponding processing action must be given.
Or handled internally.
Either declare on the function for the caller to handle it.
Generally speaking, exceptions appear in the function and need to be declared on the function.
It was found that there was only the exception name in the printed result, but there was no exception information.
Because the custom exception does not define information.
How to define exception information?
Because the operation of exception information has been completed in the parent class.
Therefore, the subclass only needs to pass the exception information to the parent class when constructing it through the super statement.
Then you can directly obtain custom exception information through the getMessage method.
Custom exceptions must be custom class inheritance Exception.
Inherit Exception reason:
An exception system has a feature: because both exception classes and exception objects are thrown.
They are all throwable. This throwability is a unique feature of the Throwable system.
Only classes and objects in this system can be operated by throws and throws.
The difference between throws and throw
throws are used on functions.
throw is used within the function.
The exception class followed by throws. Can be followed by multiple. Separated by commas.
The throw is followed by the exception object.
Example 6: There is a special subclass exception in Exception RuntimeException
If the exception is thrown in the function content, the function can be declared without declaration and the compilation will be passed.
If the exception is declared on the function, the caller can not process it, and the compilation will be done through
The reason why it is not necessary to declare the function is that the caller does not need to handle it.
When this exception occurs, I hope the program will stop, because it cannot run during running. I hope that the program will stop after the program will stop.
The programmer modified the code.
class Demo{ public int div(int x,int y)throws FuShuException /*The result of throwing or not throwing is the same*/ { if(y<0) { throw new FuShuException("The denominator has a negative number-----/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); /*Exception will appear after running this, there will be no problem with compilation*/ System.out.println("x="+x); System.out.println("over"); }}Running results:
Exception in thread "main" FuShuException: A negative number appears in the denominator ------/bu FuShu
at Demo.div(ExceptionDemo.java:7)
at ExceptionDemo.main(ExceptionDemo.java:26)
From the above results, we can see:
When custom exception: If the exception occurs, the operation cannot be continued.
Let the custom exception inherit RuntimeException.
For exceptions, there are two types:
1. Exception detected during compilation.
2. Exception that is not detected during compilation (runtime exception. RuntimeException and its subclasses)
The above article comprehensively understands the exception handling mechanism in Java is all the content I have shared with you. I hope it can give you a reference and I hope you can support Wulin.com more.