抛出一个异常
throw new ArrayIndexOutOfBoundsException();
//手动抛出 2.JVM运行时帮你抛出
public class Launcher {
public static void main(String[] args){
m1();
}
public static void m1(){
m2();
}
public static void m2(){
int[] arr = new int[2];
arr[2] =1;
}
}
/*Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Launcher.m2(Launcher.java:13)
at Launcher.m1(Launcher.java:9)
at Launcher.main(Launcher.java:6)
*/
public class Launcher {
public static void main(String[] args){
try{
m1();
}catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("finally");
}
}
public static void m1(){
m2();
}
public static void m2(){
int[] arr = new int[2];
arr[2] =1;
}
}
//catch可以有多个,顺序从小到大
自定义异常:
public class MyException extends Exception //继承自Exception
{
public MyException(){
super();
}
public MyException(String msg){
super(msg);
}
}
public static void main(String[] args)throws MyException{
throw new MyException("出现异常了");
// throw new NullPointerException();
}