异常
-
Throwable
- error
- 严重问题,不需要处理
- Exception
- RuntimeException
- 可以编译通过,需要修改代码
- 非RuntimeException
- 不能编译通过
- RuntimeException
- error
-
Throwable
- getMessage()
- toString()
- printStackTrace()
public static void method(){
int[] arr = {1,2,3}
//ArrayIndexOutOfBoundsException
System.out.println(arr[3]);
}
异常处理
- try catch
- throws
public static void method(){
try{
int[] arr = {1,2,3}
System.out.println(arr[3]);
}catch(ArrayIndexOutOfBoundsException ex){
System.out.println("xxx");
}
}
//还是得处理
public static void method() throws ArrayIndexOutOfBoundsException{
int[] arr = {1,2,3}
System.out.println(arr[3]);
}
自定义异常
- 继承Exception
public class MyException extends Exception{
public MyException(){}
public MyException(String message){
super(message);
}
}
int age=0;
if(age<0||age>100){
throw new MyException("xxx");
}