1. What is an exception
Simply put, this is due to a problem with the program running, but you can use the Try ... and catch capture processing, after which the program continues to run.
In Java, there are two types of exceptions (Exception) and errors (error). Where "Exception" is the program is not well written (or due to external reasons, network errors, file errors, etc.) caused by the "error" virtual machine itself failure (such as OutOfMemoryError), once an error occurs, we will not be able to process, the program will not continue to execute.
2. Exception Handling Process
try{ // your code}catch(Exception1 e){ //do something}catch(Exception2 e){ //do something}finally{ //do somehing}
These are the general processes for catching exceptions and handling exceptions, and the exceptions that occur in a try are captured and processed by the corresponding catch.
Finally, regardless of whether an exception occurs, it is used primarily to close some resources (such as file close, etc.).
Finally other properties:
1), Return,finally will still execute in try
2), throwing an exception in finally will overwrite the exception in the try
3), if you use return in Finally, you will not see the exception
3. Exception description (very important)
The exception description is simple, that is, you write a method, after which you indicate the type of exception you want to throw, such as
class Test{ publicvoidfuncthrowsMyException(){ //业务代码 thrownew MyException(); } }
Here's the code for the test:
main(){ try{ new Test(); t.func(); }catch(MyException e){ e.printStackTrace(); } }
Will print out the error location.
If you do not throws myexception after Func, you will get an error.
Results error: Cannot throw exception error in the body of the corresponding try statement myexception
4, RuntimeException
This exception is the only one that does not have an "exception declaration", and does not have to throw an exception by itself, but by a virtual machine.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Exceptions and exception handling