Android Capturing Errors try catch A Simple Use Tutorial

  • 2021-12-05 07:30:53
  • OfStack

Basic grammar


try{
	// Code where errors may occur 
}catch( Specific error  e){
	// If there are specific mistakes, write them, if there are no mistakes, don't write them, and if there are multiple mistakes, write multiple ones catch
	e.printStackTrace(); // Print error messages on the command line 
}catch(Exception e){
	log(e.toString());
}finally{
	// Whether an error is caught or not, 1 Code that will be executed 
}

Matters needing attention

1. When catch obtains errors, it should be from a small range to a large range, that is, specific errors should be made first, and finally all other errors should be handled by Exception The finally statement is a program segment that will be executed by 1, which is generally used to delete objects or close files, etc. Parameter err can get an error message, which is displayed using err. toString ()

Interaction between ps: try and catch

First of all, it should be clear that without try, an exception will cause the program to crash.
try can ensure the normal operation of the program, for example:


try{
    int i = 1/0;
}catch(Exception e){
 e.printStackTrace();
}

If 1 calculation, if the divisor is 0, it will report an error. If there is no try, the program will crash directly. If you use try, you can let the program run and output why it went wrong!
If try is used together with log4j, it will be of great help to the future maintenance of the program.

Then e. printStackTrace (); What do you mean?

When an exception occurs in the try statement, the statement in catch will be executed, and the java runtime system will automatically initialize Exception e in the catch brackets, that is, instantiate the object of Exception type. e is the reference name of this object. Then e (reference) automatically calls the method specified in the Exception class, and e. printStackTrace () appears; .
The printStackTrace () method means to print exception information on the command line where and why an error occurred in the program. (This is a vernacular explanation, which is easier to understand.)


try{
// Code area 
}catch(Exception e){
// Exception handling 
}

If there is an error in the code area, the handling of the written exception will be returned.


Related articles: