当前位置:网站首页>exception handling
exception handling
2022-07-24 13:14:00 【No fish in Haikou】
java In the exception handling mechanism try-catch
System.out.println(" The program begins ..."); try { String line = "a"; System.out.println(line.length()); System.out.println(line.charAt(0)); System.out.println(Integer.parseInt(line)); //try The contents after the Error statement in the statement block will not be executed System.out.println("!!!!!!!!!!"); }catch(NullPointerException e){//try No error in code ,catch Don't execute System.out.println(" A null pointer occurred !"); }catch(StringIndexOutOfBoundsException e){//catch Can write multiple System.out.println(" Subscript out of bounds !"); **catch If you catch a supertype exception , that try Its type appears in You can use this when abnormal catch Capture . We usually do this in the following situations : 1: When multiple exceptions use the same solution , Superclasses that can catch these class exceptions . 2: Final capture Exception It can avoid program interruption caused by an uncaught exception Multiple catch If there is an inheritance relationship between exceptions of , Be sure to catch subtype exceptions first , Recapture Supertype exception . Otherwise, the compilation fails .** }catch(Exception e){ System.out.println(" Anyway, there was a mistake !"); } System.out.println(" The program is over !");*/
Subclasses override the throws When declaring the method of exception throwing throws Several special rewrite rules for
public void dosome()throws IOException{} : Allow subclass methods to throw some exceptions
public void dosome(){} : You can no longer throw any exceptions
public void dosome()throws FileNotFoundException{} : Subclass exceptions that can throw exceptions from superclass methods
public void dosome()throws SQLException{}: No extra exceptions are allowed
public void dosome()throws Exception{}: It is not allowed to throw superclass methods that throw exceptions
When we call a containing throws When declaring a method that throws an exception , The compiler requires that this exception must be handled , There are two ways to deal with it
1: Use try-catch Capture exception
2: Continue to use on the current method throws The specific choice of declaring this exception depends on the problem of exception responsibility
Custom exception : We usually use custom exceptions when describing an error that satisfies syntax but does not satisfy business conditions
To customize exceptions, you need to do the following :
- 1: When defining a class name, you should know the meaning by seeing the name
- 2: Need to inherit from Exception, Inherit directly or indirectly
- 3: Provide Exception All constructs provided in
System.out.println(" The program begins ....");
String str = "a";
try {
System.out.println(Integer.parseInt(str));
}catch (Exception e){
// Output error messages to the console , Easy debug
e.printStackTrace();
// Get exception message , Usually used to prompt users
System.out.println(e.getMessage());
}
System.out.println(" The program is over ....");
//getCause- Get the reason for the exception
Throwable Is the parent of all exceptions
Exception and Error Is its derived two subclasses
Exception: Indicates that due to network failure 、 File corruption 、 Device error 、 Exceptions caused by illegal user input .
Erro: Express java Errors in the runtime environment , It cannot be handled by program
throw: Self throw exception , And generate the specified exception object
throws: Capture exception , Declaring this method will throw an exception
java Exceptions are divided into detectable exceptions , Non detection exception
Detectable exceptions : The compiler will verify , If compilation errors occur , The compiler forces exceptions or declares rules , Do not catch this exception , The compiler doesn't pass , Compilation is not allowed .
Non detection exception : Do not follow processing or declaration rules , stay When an exception occurs , The compiler does not check whether this exception has been resolved
RuntimeException: It belongs to non detection exception
Common runtime exceptions :
1.NullPointerException: Null pointer exception
reason : When the called variable is null when , Then throw the exception
2.ArrayIndexOutOfBoundsException: Array subscript out of bounds exception
reason : When the array index used exceeds the allowable range of the array , Throw the exception
3.ClassCastException: Cast exception
reason : When trying to cast an object to a subclass that is not an instance is , Throw the exception
4.IllegalArgumentException: Illegal parameter exception
reason : When an illegal parameter is passed , Throw the exception
5.NumberFormatException: The number format is abnormal
reason : When an application converts a string to a data type , But the string cannot be converted to the appropriate format , Throw the exception
Other anomalies :
1.StringIndexOutOfBoundsException: String index Super Edge exception
reason : When the specified position exceeds the length of the string , This exception occurs
2.OutOfMemoryError: out of memory
reason : When the program frequently modifies the string , Cause many “ The garbage ”GC There is no urgent recycling , Cause memory overflow to throw the exception
3.UnsupportedEncodingException: Unsupported encoding format exception
reason : When the coding format is written incorrectly , Throw the exception
4.FileNotFoundException: The system cannot find the specified file
reason : When the stream operates on a file , The computer does not have this file , Throw the exception
Please explain separately final,finally,finalize?
final: The final 、 Unalterable ----- The application rate alone is extremely low
1) Modifying variables : Variables cannot be changed
2) Modification methods : Method cannot be overridden
3) decorator : Class cannot be inherited
finally: Is the last piece of the exception handling mechanism , It can follow directly try Back ( This is less used ) Or the last one catch after .
finally It can be guaranteed that as long as the program is executed to try among , No matter what try Whether the statement inside throws an exception ,
finally The code in must be executed .
Usually, we put the operation of releasing resources into finally in , such as IO Closing after operation .
finalize: Method is object Object Method of definition , therefore java All classes in have this method , This method is when GC Method called before releasing an object , It means that after the method is called, the object will be given GC Release . If you need to rewrite this method , There should be no time-consuming operations in the method
throw and throws The difference between ?
throws It is used to declare all the exception information that a method may throw ,throws The exception is declared but not handled , But upload the exception , Who is calling , Just leave it to someone . and throw It refers to a specific exception type thrown .
边栏推荐
- Windivert: capture and modify packages
- ESP32ADC
- 27. Longest increasing subsequence
- How to draw Bezier curve and spline curve?
- setAttribute、getAttribute、removeAttribute
- The price of domestic flagship mobile phones is nearly 6000, but they can't even beat iphone12. It's clear who users choose
- Sorting method: bubble sorting (use an array to arrange a string of numbers in order (from large to small or from small to large))
- Localstorage
- About the concept of thread (1)
- Custom scroll bar
猜你喜欢

基于matlab的声音识别

Inversion of array (output in reverse order) (define an array and assign a value to output the array in reverse order)

EAS approval process related table

Handler learning

Mobilevit: challenge the end-to-side overlord of mobilenet

About thread (5) thread pool
![[paper reading] mean teachers are better role models](/img/94/f7846023d38c91d803349f43d8d414.png)
[paper reading] mean teachers are better role models

SSM online examination system including documents

28. Rainwater connection

ESP32ADC
随机推荐
About thread (5) thread pool
On node embedding
2022.07.15 暑假集训 个人排位赛(十)
Modification of EAS login interface
基于boost库的搜索引擎
binary search
31. Climb stairs
MobileViT:挑战MobileNet端侧霸主
Voice recognition based on MATLAB
Localstorage
如何画 贝赛尔曲线 以及 样条曲线?
ESP32ADC
Prototype inheritance
Pointer advanced part (1)
20201127 use markdown to draw UML diagrams, graphviz installation experience hematemesis finishing
Use of PageHelper
Deep and shallow copies of objects, extends
Experience sharing | how to use SaaS for enterprise knowledge management
Data + AI summit 2022 PPT download
29. Right view of binary tree