-
Definition of exception
-
Catch exception example
try{
//可能产生异常的代码
}catch(Type1 id1){
//处理Type1异常的代码
}catch(Type2 id2){
//处理Type2异常的代码
}catch(Type3 id3){
//处理Type3异常的代码
}
The significance of exception capture: the program does not need to be terminated when an exception occurs
3.
- What can be done after the abnormal object is caught
- String getMessage();
- String toString();
- void printStackTrace();
例
public static void main(String[] args){
try {
k();
}catch (ArrayIndexOutOfBoundsException e){
System.out.println(e.getMessage());//放在异常对象里面的值
System.out.println(e);//异常类的名字和它的message
e.printStackTrace();//打印调用堆栈,显示调用关系及发生行号
}
}
But it must not go back, and the specific processing logic depends on the needs of business logic
-
Throwing exceptions
Add throw e; (Imperative sentence, throw) in catch{}.
Effect: as if not caught -
The exception statement is
placed after the function that may throw an exception, as a statement, throws
public static void readFile() throws OpenException{
if(open() == -1){
throw new OpenException();
}
}
-
What can be "thrown out"?
Any object that inherits the Throwable class
Exception class inherits Throwable -
Throwing subclass exceptions can be caught by the parent exception catcher
Universal catcher-catch any exception
catch(Exception e){
System.out.println("Caught an exception");
}
- There can be no more exceptions in the subclass than the parent class,
but the exceptions that the parent class constructor will throw must be in the subclass constructor