try-catch-finally
try{
//可能会抛出的异常
}catch{
//对异常进行处理
}finally{
//一定会执行的代码
}
异常类
Error:系统错误,程序无法处理
Exception:程序运行时的错误,程序可以处理
Error和Exception都是Throwable的子类,Throwable、error、Exception都是存放在java.lang包中。
Error常见的子类:VirtualMachineError、AWTError、IOError
VirtualMachineError常见的子类:StackOverflowError、OutOfMemoryError,用来描述内存溢出等系统问题。
Exception常见的子类:IOException和RuntimeException
IOException存放在Java.io包中,RuntimeException存放在java.lang中
IOException常见的子类:FileLockInterruptException、FileNotFoundException、FileException,这些异常都是处理通过IO流进行文件传输的时候发生的错误。
RuntimeException常见的子类:
- 数学运算异常:ArithmeticException
- 类未定义异常:ClassNotFoundException
- 参数格式错误:illelArgumentException
- 数组下标越界:ArrayIndexOutOfBounds
- 空指针异常:NullPointException
- 方法为定义异常:NoSuchMethodError
- 其他数据类型转为数值类型不匹配时发生的异常:NumberFormatException
自己写好逻辑异常抛出,比交给虚拟机处理要负责任哈!别什么事都交给别人干,这样虚拟机会很累
public class Test{
public static void main(String []args){
int[] array = {
1,2,3};
test(array,2);
}
public static void test(int[]array,int index){
if(index>=3||index<0){
try{
throw new Exception();
}catch (Exception e){
e.printStackTrace();
}
}else{
System.out.println(array[index]);
}
}
}
异常捕获:
自动捕获、throw修饰可能抛出的异常、throws修饰可能抛出异常的方法
自定义异常:可以根据需求自定义异常
public class MyNumberException extends Exception{
pubic MyNumberException (String error){
super(error);
}
}
public class Test{
public static void main(String []args){
}
public int add(Object object) throws MyNumberException {
if(object instanceof Integer){
int num =(int)object;
return ++num;
}else{
String error = "Error";
MyNumberException myError = new MyNumberException throw myError ;
}
}
}