异常
Throwable的成员方法
方法名 | 说明 |
---|---|
public String getMessage() | 返回此 throwable的详细消息字符串 |
public String toString() | 返回此可抛出的简短描i述 |
public void printStackTrace() | 把异常的错误信息输出在控制台 |
编译时异常和运行时异常的区别
Java中的异常被分为两大类:编译时异常和运行时异常,也被称为受检异常和非受检异常所有的RuntimeException类及其子类被称为运行时异常,其他的异常都是编译时异常
-
编译时异常:必须显示处理,否则程序就会发生错误,无法通过编译
-
运行时异常:无需显示处理,也可以和编译时异常一样处理
package com.Exception; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class ExceptionDemo01 { public static void main(String[] args) { System.out.println("开始"); method(); System.out.println("结束"); method2(); } //运行时异常:无需显示处理,也可以和编译时异常一样处理 public static void method(){ try{ int[] arr={1,2,3}; System.out.println(arr[3]); }catch (ArrayIndexOutOfBoundsException e){ // e.printStackTrace(); System.out.println(e.getMessage()); // System.out.println(e.toString()); } } //编译时异常:必须显示处理,否则程序就会发生错误,无法通过编译 public static void method2(){ String s="2021-12-30"; SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); Date d = null; try { d = sdf.parse(s);//可能会出现问题的代码 } catch (ParseException e) { e.printStackTrace(); } System.out.println(d); } }
异常处理之throws
虽然我们通过try...catch..可以对异常进行处理,但是并不是所有的情况我们都有权限进行异常的处理也就是说,有些时候可能出现的异常是我们处理不了的,这个时候该怎么办呢?
针对这种情况,Java提供了throws的处理方案
格式:
throws异常类名;
注意:这个格式是跟在方法的括号后面的
-
编译时异常必须要进行处理,两种处理方案: try...catch...或者throws,如果采用throws这种方案,将来谁调用谁处理
-
运行时异常可以不处理,出现问题后,需要我们回来修改代码
自定义异常
格式:
public class 异常类名 extends Exception{
无参构造
带参构造
}
范例:
package com.Exception; import java.util.Scanner; public class CustomException extends Exception{ public CustomException() { } public CustomException(String message) { super(message); } } class Teacher{ public void checkScore(int score) throws CustomException{ if(score<0||score>100){ // throw new CustomException(); throw new CustomException("你给的分数有误,分数应该在0-100之间"); }else{ System.out.println("分数正常"); } } } class TeacherTest{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("请输入分数:"); int score= sc.nextInt(); Teacher t = new Teacher(); try { t.checkScore(score); } catch (CustomException e) { e.printStackTrace(); } } }
throws和throw的区别
throws
-
用在方法声明后面,跟的是异常类名
-
表示抛出异常,由该方法的调用者来处理
-
表示出现异常的一种可能性,并不是一定会发生这些异常
throw
-
用在方法体内,跟的是异常对象名
-
表示抛出异常,由方法体内的语句处理
-
执行throw一定抛出了某种异常