当前位置:网站首页>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 .
边栏推荐
猜你喜欢

How to draw Bezier curve and spline curve?

About thread (4) thread interaction

LeadTools 22 kit LeadTools super set

sql的where+or的用法丢失条件

3. Realize snake and basic game interface

SSM online campus album management platform

基于matlab的语音处理

现代数据架构选型:Data Fabric、Data Mesh

2022.07.21

Implementation of dynamic columns in EAS BOS doc list
随机推荐
Pointer advanced part (1)
Introduction of embedded network interface scheme and summary of driver debugging methods
The use of two-dimensional array (including the definition of two-dimensional array, the declaration and initialization of two-dimensional array (dynamic initialization, static initialization), common
Wang Ping, co-founder of Denglin Technology: Innovation + self research "dual core" drive, gpu+ enabling AI takes root | quantum bit · viewpoint sharing review
I 用c I 实现 大顶堆
34. Add two numbers
class
Implement is by yourself_ default_ constructible
Cluster construction based on kubernetes v1.24.0 (III)
[datasheet] interpretation of cs5480 data book of metering chip
FinClip 「小程序导出 App 」功能又双叒叕更新了
Symbol
selenium环境配置和八大元素定位
LEADTOOLS 22 套件 LEADTOOLS 超级套
Constraintlayout learn from 0 to 0.n
Embedded problem troubleshooting methods, network problems, SD card problems, device startup problems, serial port problems, I2C problems, SPI problems, PCIe problems, etc
Writing browser plug-ins
七月集训(第24天) —— 线段树
Windivert: capture and modify packages
【论文阅读】TEMPORAL ENSEMBLING FOR SEMI-SUPERVISED LEARNING