异常分为编译时异常和运行时异常

  • 编译时异常:必须显示处理,否则程序就会发生错误,无法通过编译
  • 运行时异常:无需显示处理,也可以和编译时异常一样处理

异常处理方式

try … catch

  1. public class test1 {
  2. public static void main(String[] args) {
  3. int [] a = {1,2,3};
  4. try {
  5. System.out.println(a[4]);
  6. }catch (ArrayIndexOutOfBoundsException e){ //异常类型
  7. System.out.println("索引越界");
  8. }
  9. }
  10. }

throws

  1. public class test1 {
  2. public static void method() throws ArrayIndexOutOfBoundsException{
  3. int [] a = {1,2,3};
  4. System.out.println(a[4]);
  5. }
  6. }
  7. public class test1 {
  8. public static void main(String[] args) {
  9. try {
  10. method();
  11. }catch (ArrayIndexOutOfBoundsException e){
  12. System.out.println("aaa");
  13. }
  14. // method();
  15. }
  16. public static void method() throws ArrayIndexOutOfBoundsException{
  17. int [] a = {1,2,3};
  18. System.out.println(a[4]);
  19. }
  20. }
  21. //throws 处理异常时并不会做处理只会抛出当前异常,调用该方法时必须再次使用try...catch再次进行处理

Throwable常用成员方法

  1. public class test1 {
  2. public static void main(String[] args) {
  3. try {
  4. method();
  5. }catch (ArrayIndexOutOfBoundsException e){
  6. System.out.println(e.getMessage()); //返回此异常的详细信息字符串
  7. System.out.println(e.toString()); //返回此可抛出的简短叙述
  8. e.printStackTrace(); //把异常的错误信息输出在控制台
  9. }
  10. // method();
  11. }
  12. public static void method() throws ArrayIndexOutOfBoundsException{
  13. int [] a = {1,2,3};
  14. System.out.println(a[4]);
  15. }
  16. }

自定义异常

  1. public class GendorException extends Exception{
  2. public GendorException(){
  3. super();
  4. }
  5. public GendorException(String msg){
  6. super(msg);
  7. }
  8. }
  9. //自定义异常调用时必须手动使用throw关键字抛出异常
  10. throw new GendorException();