异常分为编译时异常和运行时异常
- 编译时异常:必须显示处理,否则程序就会发生错误,无法通过编译
- 运行时异常:无需显示处理,也可以和编译时异常一样处理
异常处理方式
try … catch
public class test1 {public static void main(String[] args) {int [] a = {1,2,3};try {System.out.println(a[4]);}catch (ArrayIndexOutOfBoundsException e){ //异常类型System.out.println("索引越界");}}}
throws
public class test1 {public static void method() throws ArrayIndexOutOfBoundsException{int [] a = {1,2,3};System.out.println(a[4]);}}public class test1 {public static void main(String[] args) {try {method();}catch (ArrayIndexOutOfBoundsException e){System.out.println("aaa");}// method();}public static void method() throws ArrayIndexOutOfBoundsException{int [] a = {1,2,3};System.out.println(a[4]);}}//throws 处理异常时并不会做处理只会抛出当前异常,调用该方法时必须再次使用try...catch再次进行处理
Throwable常用成员方法
public class test1 {public static void main(String[] args) {try {method();}catch (ArrayIndexOutOfBoundsException e){System.out.println(e.getMessage()); //返回此异常的详细信息字符串System.out.println(e.toString()); //返回此可抛出的简短叙述e.printStackTrace(); //把异常的错误信息输出在控制台}// method();}public static void method() throws ArrayIndexOutOfBoundsException{int [] a = {1,2,3};System.out.println(a[4]);}}
自定义异常
public class GendorException extends Exception{public GendorException(){super();}public GendorException(String msg){super(msg);}}//自定义异常调用时必须手动使用throw关键字抛出异常throw new GendorException();
