The first two days were a superficial study of reflection and annotations in Java. Today, the superficial study of the exception in Java.
In Java programs, you can often see how to form statements.
try{
Catch a possible exception
}catch (Exception class exception object) {
Exception Handling Statements
}[finally{
program code that is bound to execute
}]
The flowchart is shown below.
Where the statements in finally are bound to be executed. The shutdown of various input and output streams is generally performed here.
The demo below shows a simple exception capture
int A = 1; int b = 0; Try { System.out.println (a/b);
System.out.println ("Java"); Catch (java.lang.ArithmeticException e) { // Todo:handle exception System.out.println (e); }
As we all know, the divisor cannot be 0. How the divisor in Java is 0, throws a Java.lang.ArithmeticException exception, catches the exception in the catch and outputs
Output Result: zerojava.lang.ArithmeticException:/by zero//divisor is 0
Note: System.out.println (e) can be output directly when the output anomaly is normal. You can also use the method provided in exception, E.printstacktrace ();
The code above is a simple Try{}catch () {} exception handling structure, and when an exception is caught in a try, the code that generates the exception is no longer executed, but instead jumps to the corresponding Cath statement to handle the exception.
Inheritance structure of the exception class:
Throughout the Java exception handling structure, there are the following two most commonly used classes exception and error two classes are actually throwable subclasses.
Exception:
1. Can be controllable (checked) or uncontrolled (unchecked)
2. Represents a programmer-led error
3. Should be handled at the application level
Error:
1. Always uncontrollable (unchecked)
2. Frequently used for errors that represent system errors or low-level resources
3. If possible, it should be captured at the system level
So now we're only concentrating on exception. All exceptions in Java are inherited from the exception class, all of which are subclasses of the exception.
As shown in the following:
All exceptions in the red box are the direct subclasses of the exception.
In fact, in the exception of the processing structure, but also in the object-oriented approach to processing, the steps are as follows:
1. Once an exception is generated, an instantiated object of the exception class is generated
2. Capture this exception object in a try statement
3. The resulting exception object matches each type in the catch, and the match succeeds, then executes the statement in the catch.
Because Java is polymorphic, objects of subclasses can be directly received using the object of the parent class, as well as in exception handling. So actually
Only catch (Exception e) is required at catch time, since Exception is the parent of all exceptions, all exceptions must be caught. (Upward transformation)
Of course, in a more detailed program, it is not recommended to catch exceptions, all exceptions are best captured separately.
In addition, when an exception is caught, the exception of the exception subclass can only be caught before the exception of its exception parent class can be caught.
Throws and throw keyword
1, throws
When defining a method, you can use the throws keyword declaration, using the method declared by throws, to indicate that this method does not handle the exception, and that it is given to the caller of the method to handle the exception.
So, if you throw an exception using throws on the main method, who will handle it? The answer is the JVM. All exceptions are handled by the JVM.
2. Throw
Not only can the program throw an exception, you can also artificially throw an exception, the function of the throw keyword is to throw an exception in the program, thrown when thrown is an instantiation of an exception class object.
Try { thrownew Exception ("Throw yourself in the game"); } Catch (Exception e) { System.out.println (e); }
Output: java.lang.Exception: Throw yourself in the game
Difference:
1, throws appears in the method function head, and throw appears in the function body.
2. Throws indicates that there is a possibility of an exception, which does not necessarily occur; throw throws an exception, and the throw throws a certain exception.
3, both are negative handling of the abnormal way (the negative here is not to say this way bad), just throw or may throw an exception, but not by the function to deal with the exception, the real handling of the exception by the function of the upper call processing.
In the Java interview, people often ask what is the difference between exception and runtimeexception:
Exception: (check type) must use exception handling block in program
RuntimeException: (non-checked) can not use exception handling block, if there is an exception, will be processed by the JVM.
Common runtimeexception:
ClassCastException
NullPointerException
ArrayIndexOutOfBoundsException
IllegalArgumentException
NumberFormatException
Custom exception classes, You can complete a custom exception class simply by inheriting exception or inheriting exception subclasses.
Java provides a standard exception class, and sometimes you need to use a custom exception class.
@SuppressWarnings ("Serial")classMyExceptionextendsexception{//a simple custom exception class Publicmyexception (String msg) {Super(msg); }} Public classtest{ Public Static voidMain (string[] args)throwsexception{Try{ Throw NewMyException ("Throw yourself in the game"); }Catch(Exception e) {System.out.println (e); } }}
Note:
An exception can be thrown in a catch statement in order to change the type of the exception.
If you develop a subsystem for use by other programmers, the type of exception used to represent a subsystem failure can have multiple interpretations. Servletexception is an example of such an exception type. The code executing the servlet might not want to know the details of the error, but would like to know for sure if the servlet is faulty.
Here's a basic way to catch an exception and throw it again.
Try { //access the database }catch(SQLException e) { ThrowNew servletexception ("Database error" + e.getmessage ()); }
But there is a better way to deal with it. The original exception can be re-obtained from the wrapper exception
The sample code is as follows.
classMyExceptionextendsexception{//a simple custom exception class Publicmyexception () {} Publicmyexception (String msg) {Super(msg); }} Public classtest{ Public Static voidMain (string[] args) {Try{test (); } Catch(Throwable e) {//Todo:handle ExceptionThrowable se = E.getcause ();//get the original exceptionSystem.out.println (SE); System.out.println (E.getmessage ()); } } Public Static voidTest ()throwsthrowable{Try{ //Access the database Throw NewMyException ("Throwing Away"); }Catch(MyException e) {//to wrap an exceptionThrowable es =NewException ("Database error:" +e.getmessage ()); Es.initcause (e); Throwes; } }}
This packaging technique is recommended so that you can throw advanced exceptions without losing the details of the original exception.
Today about the abnormal learning is here, in the actual development, will certainly encounter and a variety of problems, so need to take into account all the circumstances, in order to ensure the robustness of the program.
Exceptions in Java