Java exception and exception handling, Java Exception Handling
1. What is an exception?
In short, it is because the program runs a problem, but you can try... And catch, and then the program continues to run.
In java, there are two types: Exception and error. Among them, "exception" is caused by incomplete programming (or due to external reasons, network errors, file errors, etc.), and the "error" virtual machine itself (such as OutOfMemoryError ), once an error occurs, the program cannot proceed.
2. Exception Handling Process
try{ // your code}catch(Exception1 e){ //do something}catch(Exception2 e){ //do something}finally{ //do somehing}
The above is the general process of capturing and handling exceptions. exceptions that occur in try will be caught and processed by the corresponding catch.
Finally is executed regardless of whether an exception occurs. It is mainly used to close some resources (such as closing files ).
Other finally attributes:
1) return in try, finally will still execute
2) if an exception is thrown in finally, the exception in try will be overwritten.
3) if return is used in finally, no exception is found.
3. exception description (important)
Exception description is very simple, that is, you write a method, and then describe the exception type you want to throw, as shown in
Class Test {public void func () throws MyException () {// Business Code throw new MyException ();}}
The following is the test code:
main(){ try{ Test t = new Test(); t.func(); }catch(MyException e){ e.printStackTrace(); } }
The error location is printed.
If no throws MyException is thrown after func, an error is returned.
Result error: the corresponding try statement body cannot throw an exception error MyException
4. RuntimeException
This exception is the only one that does not require an "exception statement" and does not need to throw an exception manually. Instead, it is done by a virtual machine.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.