Java exception
Exception: In the Java language, an abnormal situation that occurs in the execution of a program is called an "exception". (Syntax errors and logic errors during development are not exceptions)
The abnormal events that occur during the execution of Java programs can be divided into two categories:
- Error: Serious problem that cannot be solved by the Java virtual machine. Such as: JVM system internal errors, resource exhaustion and other serious situations. Generally do not write targeted code for processing
- Exception: Other general problems caused by programming errors or accidental external factors can be handled with targeted code
Anomaly classification
Mechanisms for handling exceptions
Java adopts the exception handling mechanism, which concentrates the program code of exception handling and separates it from the normal program code, which makes the program concise and easy to maintain.
Java provides a catch-and-throw model for exception handling.
If an exception occurs during the execution of a Java program, an exception class object will be generated, and the exception object will be submitted to the Java runtime system. This process is called throwing an exception.
Generation of exception objects
Automatically generated by the virtual machine: During the running of the program, the virtual machine detects that there is a problem with the program. If the corresponding handler is not found in the current code, it will automatically create an instance object corresponding to the exception class in the background and throw— automatically thrown
Created manually by the developer: Exception exception = new ClassCastException();
The created exception object does not throw and has no effect on the program, just like creating a normal object.
If an exception is thrown in a method, the exception object will be thrown to the caller method for processing. If the exception is not handled in the caller method, it continues to be thrown to the upper method of the caller method. This process will continue until the exception is handled. This process is called catching an exception.
If an exception returns to the main() method, and main() does not handle it, the program execution terminates.
Programmers usually can only deal with Exception, and can do nothing about Error.
exception keyword
keywords | effect |
---|---|
try | Used to encapsulate code snippets where exceptions may occur |
catch | Catch the exception area. If the code encapsulated in the try is really abnormal, the program will jump to the catch area, and the exception information can be obtained in the catch area. |
throw | throw an exception to its caller |
throws | It is used to declare that an exception may occur in the current method, but there is no mechanism for handling exceptions in the method body. If the method is to be used, the caller needs to handle the possible exception information. |
finally | The code segment to be executed even if the program fails |
Common exception
abnormal | describe |
---|---|
RuntimeException | Base class for most exceptions in the java.lang package |
ArithmeticException | Arithmetic error, such as a denominator of 0 |
IllegalArgumentException | The method received an illegal parameter |
ArrayIndexOutOfBoundsException | array subscript out of bounds |
NullPointerException | Null pointer exception, attempt to access null object reference |
SecurityException | Attempt to breach security |
ClassNotFoundException | Could not load requested class |
AWTException | Exceptions in AWT |
IOException | Root class for I/O exceptions |
FileNotFoundException | cannot find file |
EOFException | end of file |
IllegalAccessException | Access to class is denied |
NoSuchMethodException | The requested method does not exist |
InterruptedException | thread interruption |
Example
public class ExceptionDemo {
public static void main(String[] args) {
String[] test=new String[9];
//将可能会出现异常的代码使用try catch包围起来
try {
String stuNo=test[9]; //此处stuNo将变成局部变量,出了代码块将无效
int a=19;
System.out.println("====>"+a/0);
} catch (ArrayIndexOutOfBoundsException e) { //捕获异常
System.out.println("数组下标越界!");
e.printStackTrace();
} catch (ArithmeticException e){
System.out.println("算术异常!");
e.printStackTrace();
}finally {
System.out.println("仍然要执行的部分");
}
try {
getArrayIndexVale(test, 10);
} catch (ArrayIndexOutOfBoundsException e) { //捕获异常
e.printStackTrace();
}
System.out.println(">==简单的输出==<"); //此处还能继续执行
}
//可以抛出多个异常
public static String getArrayIndexVale(String[] array, int index) throws ArrayIndexOutOfBoundsException, NullPointerException{
try {
return array[index];
} catch (ArrayIndexOutOfBoundsException e) {
//抛出异常
throw new ArrayIndexOutOfBoundsException("下标越界:"+index);
}
}
}
custom exception
Customize an insufficient balance exception and inherit RuntimeException
package com.Exception;
/**
* 自定义:余额不足异常
* 形成来自父类的构造方法:右键->source->Generate Constructors from Superclass
* @author Vinsmoke
*
*/
public class InsufficiFundException extends RuntimeException{
public InsufficiFundException() {
super();
}
public InsufficiFundException(String arg0, Throwable arg1, boolean arg2, boolean arg3) {
super(arg0, arg1, arg2, arg3);
}
public InsufficiFundException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
public InsufficiFundException(String arg0) {
super(arg0);
}
public InsufficiFundException(Throwable arg0) {
super(arg0);
}
}
Throw an exception
package com.Exception;
public class StuSystemManager {
public static void main(String[] args) {
payMoney();
}
/* 用于声明当前方法可能会出现异常 */
public static void payMoney() throws InsufficiFundException {
double money = 25.34;
if (money < 240) {
// 提示用户余额不足
throw new InsufficiFundException("余额不足,请充值!");
}
}
}