26.异常
1.异常概述
2.JVM处理异常的默认方案
3.异常处理
3.1 try ...catch...
4.Throwable的成员方法
public static void main(String[] args) { int[] arr = {1, 2, 3}; System.out.println("开始"); try { run(arr); } catch (ArrayIndexOutOfBoundsException throwable) { throwable.printStackTrace(); /** * java.lang.ArrayIndexOutOfBoundsException: 3 * at throwable.TryCatch.run(TryCatch.java:18) * at throwable.TryCatch.main(TryCatch.java:11) */ } System.out.println("结束"); } public static void run(int[] arr) { System.out.println(arr[3]); }
5.编译时异常和运行时异常
5.Throws处理异常
6.自定义异常
举例
public class ScoreException extends Exception { public ScoreException() { } public ScoreException(String message) { super(message); } }
public class CheckScore { public void checkScore(int score) throws ScoreException {//由于ScoreException继承自Exception,所以是编译时异常,异常需要进行处理(这里进行抛出处理,由调用者处理 if (score < 0 || score > 100) {//分数不在正常范围之内,抛出异常 throw new ScoreException("分数异常,分数应该在0-100之间"); } else { System.out.println("分数正常"); } } }
public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("请输入分数:"); int i = scanner.nextInt(); CheckScore checkScore=new CheckScore(); try { checkScore.checkScore(i); } catch (ScoreException e) { e.printStackTrace(); } }
Throws和Throw区别
补充理解throws和try...catch
throws仅仅是把异常向上抛出,交由调用它的地方去处理,其实并没有实质性的进行处理;
try...catch会处理异常,不影响程序继续向下执行